Search code examples
arraysruby-on-rails-5nested-loops

Array operations on two different arrays in ruby


I have two arrays:

  1. names = [ "John", "Jason", "Lisa" ]

  2. things = [ "Chocolate", "Sugar", "Candy" ]

The result I want is:

John- chocolate,

Jason - Sugar

Lisa - Candy

What I am doing is :

names.each do |name|
  puts "#{name} likes: "

  things.each do |item|
    puts "  #{item}"
  end
end

which gives me :

John likes: Chocolate Sugar Candy

Jason likes: Chocolate Sugar Candy

Lisa likes: Chocolate Sugar Candy


Solution

  • You can use each_with_index to use the index of names array to find the element from things array.

    names = [ "John", "Jason", "Lisa" ]
    things = [ "Chocolate", "Sugar", "Candy" ]
    
    names.each_with_index do |value, index|
      puts "#{value} likes: #{things[index]}"
    end