Loops and ranges
Ruby has loops, but you will mostly use methods that repeat instead:
3.times { puts "Hello" } # Hello, three times
1.upto(5) { |i| puts i } # 1 2 3 4 5
10.downto(8) { |i| puts i } # 10 9 8
(1..5).each { |i| puts i * i } # 1 4 9 16 25
The part in curly braces is a block: a chunk of code passed to the method, which runs it as many times as it needs. |i| names the value the method hands to the block on each run.
For longer blocks, use do ... end:
(1..3).each do |round|
puts "Round #{round}"
puts "Fight!"
end
Ranges
1..5 includes 5. 1...5 (three dots) stops before 5. Ranges work with letters too: ('a'..'e').to_a gives ["a", "b", "c", "d", "e"].
while
The classic loop exists too, for when you do not know how many rounds you need:
savings = 0
savings += 15 while savings < 100
Your task
- Print
Hip hip hooray!three times usingtimes. - Write
factorial(n): 1 × 2 × ... × n (andfactorial(0)is 1). - Write
fizzbuzz(n): returns"FizzBuzz"ifndivides by 15,"Fizz"if by 3,"Buzz"if by 5, otherwise the number as text (n.to_s).
A method is defined with def name(params) ... end; the value of its last line is returned.