Chapter 4: Conditionals and Recursion

4.1 The modulus operator

#!/usr/bin/env ruby

quotient = 7 / 3
remainder = 7 % 3
#puts quotient, remainder

4.2 Conditional execution

#!/usr/bin/env ruby

x = 6
if x > 0
  puts "x is positive"
end

4.3 Alternative execution

#!/usr/bin/env ruby

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

#!/usr/bin/env ruby

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

#!/usr/bin/env ruby

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

#!/usr/bin/env ruby

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 # INTERESTING, SEE 4.7
end

#print_logarithm(8)
#print_logarithm(0)
#print_logarithm(-8)

4.7 Type conversion

4.8 Recursion

#!/usr/bin/env ruby

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

#n_lines(3)

4.9 Stack diagrams for recursive methods

4.10 Convention and divine law

4.11 Glossary

4.12 Exercises

GNU Free Documentation License Valid HTML Valid CSS Built with BBEdit
Friendly links for Google “juice”