"Cyan", 2 => "Magenta", 3 => "Yellow", 4 => "Blac" /> "Cyan", 2 => "Magenta", 3 => "Yellow", 4 => "Blac" /> "Cyan", 2 => "Magenta", 3 => "Yellow", 4 => "Blac"/>

How to convert array to hash in Ruby using indices?

135 views Asked by At

I want to convert the array of this:

["Cyan", "Magenta", "Yellow", "Black"]

to hash like this:

{1 => "Cyan", 2 => "Magenta", 3 => "Yellow", 4 => "Black"}

How could I make it in Ruby language?

I've tried using this code

color = ["Cyan", "Magenta", "Yellow", "Black"]
var.each_with_object({}) do |color_hash| 
   color_hash 
end

But i've got error. What is the correct code for that?

3

There are 3 answers

0
marmeladze On

This might work

["Cyan", "Magenta", "Yellow", "Black"].each_with_index.map {|e, i| [i+1, e] }.to_h
4
Rajagopalan On
a = %w[Cyan Magenta Yellow Black]

p a.map.with_index(1) { |value, index| [index, value] }.to_h

Output

{1=>"Cyan", 2=>"Magenta", 3=>"Yellow", 4=>"Black"}

Another way

colors = %w[Cyan Magenta Yellow Black]
color_map = Hash[(1..colors.size).to_a.zip(colors)]
p color_map
0
mechnicov On

You on the right way and can combine Enumerable#each_with_object with Enumerator#with_index such way:

colors = %w[Cyan Magenta Yellow Black]

colors.each_with_object({}).with_index(1) { |(color, result), id| result[id] = color }
# => {1=>"Cyan", 2=>"Magenta", 3=>"Yellow", 4=>"Black"}

Since you tagged your question with , you can use Enumerable#index_by (again with plain Ruby Enumerator#with_index)

colors = %w[Cyan Magenta Yellow Black]

colors.index_by.with_index(1) { |_, id| id }
# => {1=>"Cyan", 2=>"Magenta", 3=>"Yellow", 4=>"Black"}