Ruby Methods (Part 1)

Watch out! This tutorial is over 7 years old. Please keep this in mind as some code snippets provided may no longer work or need modification to work on current systems.
Tutorial Difficulty Level    

Functions (and later methods) are defined with def. Parameters are given, without types of course. Default values may be provided. Note that when we send an integer, the method does not change the value sent.

# Square the number
def sqr(x)
    return x*x
end

# See how it works.
(rand(4) + 2).times {
    a = rand(300)
    print a,"^2 = ", sqr(a), "\n"
}
print "\n"

# Don't need a parm.
def boom
    print "Boom!\n"
end
boom
boom

# Default parms
print "\n"
def line(cnt, ender = "+", fill = "-")
    print ender, fill * cnt, ender, "\n"
end
line(8)
line(5,'*')
line(11,'+','=')

# Do they change?
def incr(n)
    n = n + 1
end
a = 5
incr(a)
print a,"\n"