MC logo

Methods II

  Ruby Example Code

<<Methods I def2.rb Methods III>>
# Place the array in a random order.  Floyd's alg.
def shuffle(arr)
    for n in 0...arr.size
        targ = n + rand(arr.size - n)
        arr[n], arr[targ] = arr[targ], arr[n] if n != targ
    end
end

# Make strange declarations.
def pairs(a, b)
    a << 'Insane'
    shuffle(b)
    b.each { |x| shuffle(a); a.each { |y| print y, " ", x, ".\n" } }
end
first = ['Strange', 'Fresh', 'Alarming']
pairs(first, ['lemonade', 'procedure', 'sounds', 'throughway'])
print "\n", first.join(" "), "\n"

See:Programming RubyRuby Manual

Here's another use of methods. Notice that when we send an array as a parameter, changes in the function do update the value to the caller.

One incidental thing we have not seen before is parallel assignment in the shuffle function which exchanges two values.
<<Methods I Methods III>>