I am attempting to write a method named my_transform
that takes an array as follows:
items = [\"Aqua\", \"Blue\", \"Green\", \"Red\", \"Yellow\"]
>
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}
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}