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

后端 未结 8 1051
谎友^
谎友^ 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 20:07
    h = arr.each_with_object({}) { |v,h| h[v] = f(v) }
    
    0 讨论(0)
  • 2020-12-12 20:19

    This is what I would probably write:

    h = Hash[arr.zip(arr.map(&method(:f)))]
    

    Simple, clear, obvious, declarative. What more could you want?

    0 讨论(0)
提交回复
热议问题