Converting Ruby array into a hash

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

    Most Rubies

    This works at least as far back as Ruby 1.9.3.

    # Verbose, but flexible!
    def hasherize *array
      hash = {}
      array.flatten!
      array.each_with_index { |key, value| hash[key] = value }
      hash
    end
    
    # Pass a single array as an argument.
    hasherize %w(Aqua Blue Green Red Yellow)
    #=> {"Aqua"=>0, "Blue"=>1, "Green"=>2, "Red"=>3, "Yellow"=>4}
    
    # Pass multiple arguments to the method.
    hasherize :foo, :bar, :baz
    #=> {:foo=>0, :bar=>1, :baz=>2}
    

    Ruby >= 2.1.0

    If you're running a recent Ruby, you can simplify the above to:

    def hasherize *array
      array.flatten.each_with_index.to_h
    end
    

    The results will be the same as above, but the Array#to_h method simplifies the code a lot. However, you still need to flatten the array to avoid results like:

    #=> {["Aqua", "Blue", "Green", "Red", "Yellow"]=>0}
    

提交回复
热议问题