To convert the array cols = %w(black brown red)
to the hash cols = { "black" => '0', "brown" => '1', "red" => '2' }
in Ruby, you can use the each_with_index
method along with the to_h
method.
Here's the code to achieve this conversion:
main.rb114 chars5 lines
Output:
main.rb41 chars2 lines
In this code, each_with_index
is used to iterate over the elements of the cols
array along with their respective indices. For each element, a new array is created with the color as the key and the index converted to a string as the value. Finally, to_h
is used to convert the resulting array of arrays to a hash.
Note that the order of elements in the resulting hash may not be the same as the original array since hashes do not preserve order in Ruby.
gistlibby LogSnag