3

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
3
  • 3
    "So far, I have achieved this" - it usually helps expose what exact problem you have if you post the code that you used to achieve it. Commented Aug 15, 2018 at 9:54
  • You might want to look at inject, map and with_index Commented Aug 15, 2018 at 10:00
  • @Amadan Yup. I was in transit, hence could not paste the code at that point. I have updated what I have tried and it's messy. Commented Aug 15, 2018 at 11:38

5 Answers 5

5

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]}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

with_index accepts an argument: with_index(1) { |a, i| [i, a] }.to_h.
2

What about just iterating with index over @vehicle_numbers and get other values by that index?

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

Comments

1

Just out of curiosity:

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

Comments

0

You can try this one. It works for me.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.