MC logo

Methods III

  Ruby Example Code

<<Methods II def3.rb Exceptions I>>
# Add the strings before and after around each parm and print
def surround(before, after, *items)
    items.each { |x| print before, x, after, "\n" }

surround('[', ']', 'this', 'that', 'the other')
print "\n"

surround('<', '>', 'Snakes', 'Turtles', 'Snails', 'Salamanders', 'Slugs',
print "\n"

def boffo(a, b, c, d)
    print "a = #{a} b = #{b}, c = #{c}, d = #{d}\n"

# Use * to adapt between arrays and arguments
a1 = ['snack', 'fast', 'junk', 'pizza']
a2 = [4, 9]
boffo(17, 3, *a2)

The * is used to adapt between arrays and parameter or argument lists. In a call, a * before an array treats the array members as separate arguments. A * before the last parameter causes it to receive all remaining arguments as an array.
<<Methods II Exceptions I>>