Cleanest way to create a Hash from an Array

前端 未结 5 1440
南方客
南方客 2021-02-01 15:56

I seem to run into this very often. I need to build a Hash from an array using an attribute of each object in the array as the key.

Lets say I need a hash of example us

5条回答
  •  礼貌的吻别
    2021-02-01 16:25

    In case someone got plain array

    arr = ["banana", "apple"]
    Hash[arr.map.with_index.to_a]
     => {"banana"=>0, "apple"=>1}
    

提交回复
热议问题