Ruby/Range/with for

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

a for loop and an inclusive string range

for i in "a".."z"
  print i
end



An example of a for loop that prints out a times table (from 1 to 12) for the number 2

for i in 1..12
  print "2 x " + i.to_s + " = ", i * 2, "\n"
end



Drop the do. It isn"t required, but you have to keep end:

for i in 1..5
  print i, " "
end
# => 1 2 3 4 5



If you want to do the for loop on one line, you have to throw in the do

for i in 1..5 do print i, " " end # => 1 2 3 4 5



The for loop

for i in 1..5 do
  print i, " "
end
# => 1 2 3 4 5



With nested for loops, you can easily print out times tables from 1 to 12:

for i in 1..12
  for j in 1..12
    print i.to_s + " x " + j.to_s + " = ", j * i, "\n"
  end
end