Ruby hash equivalent of JavaScript's object initializer ES6 shorthand
No, there is no such shorthand notation.
Short answer no.
Longer answer
Shugo Maeda proposed a patch for this in 2015 (you can read the details about this here: https://bugs.ruby-lang.org/issues/11105).
At the time Matz wasn't into the idea, but might be willing to change his mind in the future.
In the mean time - you can make use of Shugo's patch and patch your own version of Ruby to have ES6 hash literals yourself!
To patch Ruby to add the hashes do the following:
1) Download the patch from here https://gist.github.com/thechrisoshow/1bb5708933d71e0e66a29c03cd31dcc3 (currently works with Ruby 2.5.0)
2) Use RVM to install a patched version of this Ruby. i.e.
rvm install 2.5.0 -n imphash --patch imphash.patch
Then you can use RVM to select the patched version of Ruby:
rvm use 2.5.0-imphash
(Imphash is short for implicit hash)
Not built in to the language. But what do you think of this?
https://gist.github.com/smtlaissezfaire/e81356c390ae7c7d38d435ead1ce58d2
def hash_shorthand(source_binding, *symbols)
hash = {}
symbols.each do |symbol|
hash[symbol] = source_binding.local_variable_get(symbol)
end
hash
end
$ irb -r './hash_shorthand.rb'
>> x = 10
>> y = 20
>>
>> puts hash_shorthand(binding, :x, :y)
{:x=>10, :y=>20}
Only downside is that you'll need to pass the binding to get access to the local variables.