In Javascript I can do this:
myVar = 1
obj = { myVar }
obj.myVar == 1 // true
In Ruby it's only possible to do something similar to this in methods, with keyword arguments:
def foo(a:, b:)
[a,b]
end
foo(a: 1, b: 2) # [1,2]
In practice I find this makes the code more verbose. Rather than naming a variable once, as I'd do with sequential arguments, I have to name it twice in order to send it as an argument:
def method_1(a:, b:)
method_2(a: a, b: b) # repetition is here
end
I'm aware of the **
operator which serves as a splat for keyword arguments. But I'd rather not put splats in my method definitions, because it makes code less comprehensible.
I'm not saying keyword arguments are useless (it's clearer than parsing an options
hash) but they would be more useful if they supported regular hash construction, like in Javascript.
Anyway, I'm wondering if there is any way to do this in Ruby itself, or if I should look to another language.
a: a
?