Chapter 4: Conditionals and Recursion
4.1 The modulus operator
quotient = 7 / 3
remainder = 7 % 3
4.2 Conditional execution
x = 6
if x > 0
puts "x is positive"
end
4.3 Alternative execution
x = 6
if x % 2 == 0
puts "x is even"
else
puts "x is odd"
end
def print_parity(x)
if x % 2 == 0
puts "x is even"
else
puts "x is odd"
end
end
print_parity(17)
number = 17
print_parity(number)
4.4 Chained conditionals
x = -6
if x > 0
puts "x is positive"
elsif x < 0
puts "x is negative"
else
puts "x is zero"
end
4.5 Nested conditionals
x = -6
if x == 0
puts "x is zero"
else
if x > 0
puts "x is positive"
else
puts "x is negative"
end
end
4.6 The return statement
def print_logarithm(x)
if x <= 0
puts "Positive numbers only, please."
return
end
result = Math.log(x)
puts "The log of x is " + result.to_s
end
4.7 Type conversion
4.8 Recursion
def countdown(n)
if n == 0
puts "Blastoff!"
else
puts n
countdown(n-1)
end
end
countdown(3)
def new_line
puts
end
def three_line
new_line; new_line; new_line;
end
def n_lines(n)
if n > 0
puts ""
n_lines(n-1)
end
end
4.9 Stack diagrams for recursive methods
4.10 Convention and divine law
4.11 Glossary
4.12 Exercises
Friendly
links for Google “juice”