Converting Ruby array into a hash

后端 未结 6 2039
甜味超标
甜味超标 2021-01-29 15:54

I am attempting to write a method named my_transform that takes an array as follows:

items = [\"Aqua\", \"Blue\", \"Green\", \"Red\", \"Yellow\"]
         


        
6条回答
  •  逝去的感伤
    2021-01-29 16:44

    You can also try this.

    e.g.

    items = ["Aqua", "Blue", "Green", "Red", "Yellow"]
    
    items.inject({}) do |tmphash, (k,v)|
      tmphash[k] = items.index(k)
      tmphash
    end
    
    ## OUTPUT
    
    {"Aqua"=>0, "Blue"=>1, "Green"=>2, "Red"=>3, "Yellow"=>4}
    

提交回复
热议问题