I'm trying to convert 3 different arrays into a single Hash.
Here are the 3 arrays
@vehicle_numbers = ["Registration Number 1", "Registration Number 2", "Registration Number 1"]
@vehicle_colors = ["red", "blue", "green"]
@allocated = [true, true, true]
What I'm trying to achieve is
{1=> ["Registration Number 1", "red", true], 2=> ["Registration Number 2", "blue", true]}
So far, I have achieved this
{1=> ["Registration Number 1", "red"], 2=>["Registration Number 2", "red"]}
I'm trying to add allocated key into the existing hash, but I'm not able to figure out, what is wrong with it.
@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
You can do it in one line.
@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]}
[@vehicle_numbers, @vehicle_colors, @allocated].transpose.map.with_index { |a, i| [i + 1, a] }.to_h
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With