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

后端 未结 8 1091
谎友^
谎友^ 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条回答
  •  旧时难觅i
    2020-12-12 19:55

    in addition to the answer of Vlado Cingel (I cannot add a comment yet, so I added an answer).

    Inject can also be used in this way: the block has to return the accumulator. Only the assignment in the block returns the value of the assignment, and an error is reported.

    array = ["apples", "bananas", "coconuts", "watermelons"]
    hash = array.inject({}) { |h,fruit| h[fruit]= f(fruit); h }
    

提交回复
热议问题