Ruby/Statement/times

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

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

Содержание

Although do and end are encouraged for multiple-line code blocks, curly brackets make the code easier to read on a single line.

5.times { puts "Test" }



basic way to implement a loop

5.times do puts "Test" 
end



Do calculation in times block

10.times { |i| print 5*i, " " }



Iterating Through Blocks

# Starting with zero, the times method iterates value times.
10.times { |i| print i, " " }



Repeating and Making Choices

3.times do 
    print "Enter a value: " 
    STDOUT.flush 
    value = gets.to_i 
 
    if value == 1 
        puts "one" 
    elsif value == 2 
        puts "two" 
    else 
        puts "many" 
    end 
    puts 
end



The times Method and for loop

# The times method (from Integer) is convenient and concise. Compare this for loop:
for i in 1..10
  print i, " "
end
# => 1 2 3 4 5 6 7 8 9 10
# with this call to times:
10.times { |i | print i, " " } # => 0 1 2 3 4 5 6 7 8 9



To iterate a set number of times, use the times iterator:

5.times do
  puts "You"re going to see this five times, whether you want to or not!"
end



use a value in a variable with times

five = 5
five.times do
  puts "You"re going to see this five times, whether you want to or not!"
end