how to change `cols = %w(black, brown, red)` to this: `cols = { "black" => '0', "brown" => '1', "red" => '2'}` in ruby

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.rb
cols = %w(black brown red)
cols = cols.each_with_index.map { |color, index| [color, index.to_s] }.to_h

puts cols
114 chars
5 lines

Output:

main.rb
{"black"=>"0", "brown"=>"1", "red"=>"2"}
41 chars
2 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.

related categories

gistlibby LogSnag