February 2, 2004 Intro to Ruby Slide #15
Prev Next

Functions

Functions are declared with the def keyword:
     def factorial(n)
         if n == 0
             return 1
         else
             return n * factorial(n-1)
         end
     end

As in Perl, functions automatically return the last statement executed, so that function could be rewritten as
     def factorial(n)
         if n == 0
             1
         else
             n * factorial(n-1)
         end
     end

Subroutines can be given default values:
     def foo (x, debug=false)
         puts "in foo, x = #{x}" if debug
         ...
     end


Prev Copyright © 2004 Walter C. Mankowski Next