?

Log in

No account? Create an account
fragglet [userpic]

Ruby parameter passing

July 19th, 2006 (09:33 am)

This is about parameter passing in Ruby. This is more complicated than you would expect.

First, you have your normal ("C-style") parameters:

def func(a, b, c)
    puts a, b, c
end

func(1, 2, 3)

Here, the parameters are named, and the order when passing determines assignment. You can also do this:
def func(a, b, c=3)
    puts a, b, c
end

func(1, 2)
func(1, 2, 5)

Here, the third parameter has a default, so it can be omitted if desired, in order to use the default value.

Next, the '*' operator lets you do variable argument lists. All "extra" arguments get put into an array in the variable specified.
def func(a, b, *otherargs)
    puts a
    puts b
    otherargs.each { |arg| puts arg }
end

# a=1, b=2, otherargs=[3,4,5]
func(1, 2, 3, 4, 5)
# a=1, b=2, otherargs=[]
func(1, 2)

Next, there is a clever shorthand that lets you use the hash table '=>' operator when calling functions, effectively giving you a sort of "named argument" capability. If you specify a bunch of hash pairs, they get collected together into a hash assigned to the last argument. Ruby on Rails seems to make fairly heavy use of this one.
def func(a, b, hash)
    hash.each_pair do |key, val|
        puts "#{key} -> #{val}"
    end
end

# This:

func(1, 2, "first" => true, "next" => 5, "last" => "hi")

# is equivalent to this:

func(1, 2, { "first" => true, "next" => 5, "last" => "hi" } )


Finally, you can get a reference to the code block passed to the function using the '&' operator:
def func(a, &block)
    puts a
    block.call()
end

func(1) do 
    puts "calling block!"
end

Comments

Posted by: the_ophiolater (the_ophiolater)
Posted at: October 28th, 2006 07:17 pm (UTC)

You should have used common lisp.

Posted by: robhu (ex_robhu)
Posted at: April 30th, 2007 11:25 am (UTC)

I believe Matz is looking in to adopting some changes to how parameters are passed to more fluidly support this in Ruby 2.0.

2 Read Comments