如何使用索引在 Ruby 中将数组转换为散列?

问题描述 投票:0回答:3

我想转换这个数组:

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

像这样散列:

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

如何用 Ruby 语言制作它?

我试过使用这个代码

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

但是我有错误。正确的代码是什么?

ruby-on-rails ruby
3个回答
0
投票

这可能有用

["Cyan", "Magenta", "Yellow", "Black"].each_with_index.map {|e, i| [i+1, e] }.to_h

0
投票
a = %w[Cyan Magenta Yellow Black]

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

输出

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

另一种方式

colors = ["Cyan", "Magenta", "Yellow", "Black"]
color_map = Hash[1..colors.size.zip(colors)]
puts color_map

0
投票

你在正确的方式,可以结合

Enumerable#each_with_object
Enumerator#with_index
这样的方式:

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"}

由于您使用 标记了您的问题,您可以使用

Enumerable#index_by
(再次使用普通 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"}
© www.soinside.com 2019 - 2024. All rights reserved.