Ruby hash equivalent of JavaScript's object initializer ES6 shorthand

前端 未结 5 472
心在旅途
心在旅途 2021-01-07 23:02

In JavaScript ES6 we can create objects where variable names become keys like this:

> let a = \'aaa\'
\'aaa\'

> let b = \'bbb\'
\'bbb\'

> { a, b }         


        
5条回答
  •  再見小時候
    2021-01-07 23:11

    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)

提交回复
热议问题