1

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?

mechnicov
  • 12,025
  • 4
  • 33
  • 56
  • "I've got error" is not a precise enough error description for us to help you. *What* doesn't work? *How* doesn't it work? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ? – Jörg W Mittag Apr 16 '23 at 11:03

3 Answers3

2

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"}
mechnicov
  • 12,025
  • 4
  • 33
  • 56
0

This might work

["Cyan", "Magenta", "Yellow", "Black"].each_with_index.map {|e, i| [i+1, e] }.to_h
marmeladze
  • 6,468
  • 3
  • 24
  • 45
0
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
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29