gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:42:20 24 4
gpt4 key购买 nike

我正在尝试将 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"]}

我正在尝试将分配的 key 添加到现有哈希中,但我无法弄清楚它有什么问题。

@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

最佳答案

你可以一行完成。

@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]}

关于arrays - Ruby - 转换多个数组以生成哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51856533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com