A
A
arruah2019-01-31 02:08:58
ruby
arruah, 2019-01-31 02:08:58

How to loop through two arrays in ruby?

I'm learning ruby ​​in a course.
There is a task:

Написать программу, которая печатает список товаров и их цены в виде чека. Товары и
их цены хранятся в программе в двух массивах одинаковой длины:
items = ["Chocolate", "Cheese", "Milk", "Bread";]
prices = [3, 15, 4.5, 2.15]
Пример вывода:
Name Price
Chocolate 3.00
Cheese 15.00
Milk 4.50
Bread 2.15

I wrote this:
goods = ["Chocolate", "Cheese", "Milk", "Bread"]
prices = [3, 15, 4.50, 2.15]
puts "            Name" + "      " + "Price"

goods.each do |g|
  prices.each do |p|
#    puts sprintf("%20s", g.to_s) + "     " + sprintf("%6i", p)
     puts g.to_s + "     " + p.to_s 
    break
  end
end

I can’t figure out how to iterate through the nested loop with prices, since only names are iterated in the output.
Name      Price
Chocolate     3
Cheese     3
Milk     3
Bread     3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-01-31
@0xD34F

No nested loop needed. Add indexes, and access the elements of the second array:

goods.each.with_index do |n, i|
  puts n + " " + prices[i].to_s
end

UPD. Or you can concatenate arrays:
print goods.zip(prices).map{|n| n.join(" ")}.join("\n")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question