Ruby-转换多个数组以生成哈希

时间:2018-08-15 09:51:22

标签: arrays ruby hash

我正在尝试将3个不同的数组转换为单个哈希。

这是3个数组

@vehicle_numbers = ["Registration Number 1", "Registration Number 2", "Registration Number 1"]
@vehicle_colors = ["red", "blue", "green"]
@allocated = [true, true, true]

我想要实现的是

{1=> ["Registration Number 1", "red", true], 2=> ["Registration Number 2", "blue", true]}

到目前为止,我已经实现了

{1=> ["Registration Number 1", "red"], 2=>["Registration Number 2", "red"]}

我正在尝试将分配的密钥添加到现有的哈希中,但是我无法弄清楚这是怎么回事。

@lines.each do |line|
      @method_name = line.split[0]
      if @method_name == "park"
        @vehicle_numbers << @vehicle_number = line.split[1]
        @vehicle_colors << @vehicle_color = line.split[2]
        @vehicle_info["#{@vehicle_number}"] = @vehicle_color
        # puts @vehicle_info["#{@vehicle_number}"] = @vehicle_color
      end
    end
    @slots = 1.step(@vehicle_numbers.count, 1).to_a
    @vehicle_info = Hash[(@slots).zip @vehicle_info ]
    @slots.each do |slot|
      puts "Allocated slot number: #{slot}"
    end
    puts @vehicle_info

5 个答案:

答案 0 :(得分:5)

您可以一行完成。

@vehicle_numbers.zip(@vehicle_colors, @allocated).each.with_index(1).to_h.invert
# => {1=>["Registration Number 1", "red", true], 2=>["Registration Number 2", "blue", true], 3=>["Registration Number 1", "green", true]}

答案 1 :(得分:4)

[@vehicle_numbers, @vehicle_colors, @allocated].transpose.map.with_index { |a, i| [i + 1, a] }.to_h

答案 2 :(得分:2)

仅遍历@vehicle_numbers的索引并通过该索引获取其他值怎么办?

@vehicle_numbers.map.with_index do |vehicle_number, index|
  [index + 1, [vehicle_number,  @vehicle_colors[index], @allocated[index]]]
end.to_h

答案 3 :(得分:1)

只是出于好奇:

(1..3).zip(
  [@vehicle_numbers, @vehicle_colors, @allocated].transpose
).to_h 

答案 4 :(得分:0)

您可以尝试这个。它对我有用。

hash = (1..3).zip([@vehicle_numbers.map(&:to_s), @vehicle_colors.map(&:to_s), @allocated].transpose).to_h