fragglet (fragglet) wrote,
fragglet
fragglet

Ruby parameter passing

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
Subscribe

  • Goodbye Livejournal

    I've decided to discontinue using Livejournal. The posts on this blog will remain up but future posts will appear on Google+.

  • Initialisation dogma considered harmful

    In C, variables aren't initialised to a value automatically. I've seen some people who seem to have adopted a rule of initialising every variable…

  • How to coerce gdb into giving a backtrace

    When debugging with gdb, I sometimes encounter a problem in getting it to recognise a stack trace. Sometimes it only gives a few function calls, or…

  • 2 comments
  • 2 comments

Comments for this post were locked by the author