iterate over a list in ruby

In Ruby, you can iterate over a list (or an array) using different types of loops. Here are a few examples:

  1. Using each method:
main.rb
list = [1, 2, 3, 4, 5]
list.each do |item|
  puts item
end
59 chars
5 lines
  1. Using for loop:
main.rb
list = [1, 2, 3, 4, 5]
for item in list do
  puts item
end
59 chars
5 lines
  1. Using while loop:
main.rb
list = [1, 2, 3, 4, 5]
i = 0
while i < list.length do
  puts list[i]
  i += 1
end
82 chars
7 lines

All of the above loops will output the same result:

main.rb
1
2
3
4
5
10 chars
6 lines

You can choose the loop that suits your needs depending on the situation.

related categories

gistlibby LogSnag