In Ruby, how do I make a hash from an array?

后端 未结 8 1070
谎友^
谎友^ 2020-12-12 19:28

I have a simple array:

arr = [\"apples\", \"bananas\", \"coconuts\", \"watermelons\"]

I also have a function f that will perfo

8条回答
  •  伪装坚强ぢ
    2020-12-12 19:59

    Ruby 2.6.0 enables a shorter syntax by passing a block to the to_h method:

    arr.to_h { |a| [a, f(a)] }
    

提交回复
热议问题