Nesting and a little Proc.
Zed Shaw wrote a great tutorial on Ruby. Going through it now, I always like going through these things, because experienced programmers might slip up and give me something useful:
puts "ADDING #{a} + #{b}" a + b end def subtract(a, b) puts "SUBTRACTING #{a} - #{b}" a - b end def multiply(a, b) puts "MULTIPLYING #{a} * #{b}" a * b end def divide(a, b) puts "DIVIDING #{a} / #{b}" a / b end
Novice:
puts "Let's do some math with just functions!" age = add(30, 5) height = subtract(78,4) weight = multiply(90, 2) iq = divide(100, 2)
Programmer:
puts "Age: #{age}, Height: #{height}, Weight: #{weight}, IQ: #{iq}" # A puzzle for the extra credit, type it in anyway. puts "Here is a puzzle." what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) puts "That becomes: #{what} Can you do it by hand?"
Hacker (of course my own spin):
the_multiplier = Proc.new {|a, *b| b.collect {|i| i*a }}
puts “Maybe you could’ve done that nested thing by hand… But if you got this right: #{the_multiplier.call(what,50,2,31)}, then you’ve impressed me”