Download this source
# Some basic method stuff
# This is a method
def amethod(a, b)
print a
print b
print "\n"
end
# call the regular method
amethod("Hello","World")
amethod(15,24)
amethod("Hello",25)
# Varargs method (array argument)
def var_args_method(*args)
# Let's use 'p' so we can see the actual array
p args
end
list = ["Ross","Rosie","Jake","Dozer"]
var_args_method("This","is")
var_args_method("The","Same","Method")
var_args_method(76)
# inverse of the above allows us to pass in array elements
var_args_method(list) # <-- One arg, the array
var_args_method(*list) # <-- Three args
# default param values
def with_default(a = "default")
print a, "\n"
end
with_default
with_default "Non-default"
# Blocks
#
# Any method can take a block, and use 'yield' to call it.
# We can figure out whether there's a block with
# block_given? but usually you just yield, since Ruby will
# give a nice ArgumentError if no block was supplied.
def yielder(it, num)
num.times { yield it }
end
yielder("Hi!",2) { |param| puts param }
# You can also explicitly declare a method to take a block.
# You have to use this form if you want to do anything
# beyond calling the block.
#
# Blocks are procs for this purpose.
def blocky(&block)
p block # don't call - inspect
end
Running this outputs:
HelloWorld
1524
Hello25
["This", "is"]
["The", "Same", "Method"]
[76]
[["Ross", "Rosie", "Jake", "Dozer"]]
["Ross", "Rosie", "Jake", "Dozer"]
default
Non-default
Hi!
Hi!

