Converting Ruby array into a hash

后端 未结 6 1888
甜味超标
甜味超标 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:28

    I would use Array#to_h:

    items = ["Aqua", "Blue", "Green", "Red", "Yellow"]
    items.each_with_index.to_h
    #=> { "Aqua"=>0, "Blue"=>1, "Green"=>2, "Red"=>3, "Yellow"=>4 }
    

    Note that to_h was introduced in Ruby 2.1

    Using to_h your my_transform method could look like this:

    def my_transform(items)
      items.each_with_index.to_h
    end
    

提交回复
热议问题