What is the best way to convert an array to a hash in Ruby

后端 未结 11 2022
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 18:18

In Ruby, given an array in one of the following forms...

[apple, 1, banana, 2]
[[apple, 1], [banana, 2]]

...what is the best way to convert

11条回答
  •  忘掉有多难
    2020-11-28 18:41

    The best way is to use Array#to_h:

    [ [:apple,1],[:banana,2] ].to_h  #=> {apple: 1, banana: 2}
    

    Note that to_h also accepts a block:

    [:apple, :banana].to_h { |fruit| [fruit, "I like #{fruit}s"] } 
      # => {apple: "I like apples", banana: "I like bananas"}
    

    Note: to_h accepts a block in Ruby 2.6.0+; for early rubies you can use my backports gem and require 'backports/2.6.0/enumerable/to_h'

    to_h without a block was introduced in Ruby 2.1.0.

    Before Ruby 2.1, one could use the less legible Hash[]:

    array = [ [:apple,1],[:banana,2] ]
    Hash[ array ]  #= > {:apple => 1, :banana => 2}
    

    Finally, be wary of any solutions using flatten, this could create problems with values that are arrays themselves.

提交回复
热议问题