Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Converting Multiple arrays to generate a Hash

Tags:

arrays

ruby

hash

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
like image 560
Kedarnag Mukanahallipatna Avatar asked Mar 03 '26 06:03

Kedarnag Mukanahallipatna


2 Answers

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]}
like image 61
Arup Rakshit Avatar answered Mar 04 '26 18:03

Arup Rakshit


[@vehicle_numbers, @vehicle_colors, @allocated].transpose.map.with_index { |a, i| [i + 1, a] }.to_h
like image 20
Leo Avatar answered Mar 04 '26 19:03

Leo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!