Ruby hash equivalent of JavaScript's object initializer ES6 shorthand

前端 未结 5 471
心在旅途
心在旅途 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:30

    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.

提交回复
热议问题