views:

108

answers:

3

Hello,

I'm very new to ruby and I'm trying to write a web application using the rails framework. Through reading I've seen methods being called like this:

some_method "first argument", :other_arg => "value1", :other_arg2 => "value2"

Where you can pass an unlimited number of arguments.

How do you create a method in ruby that can be used in this way?

Thanks for the help.

+10  A: 

That works because Ruby assumes the values are a Hash if you call the method that way.

Here is how you would define one:

def my_method( value, hash = {})
  # value is requred
  # hash can really contain any number of key/value pairs
end

And you could call it like this:

my_method('nice', {:first => true, :second => false})

Or

my_method('nice', :first => true, :second => false )
Doug Neiner
+2  A: 

This is actually just a method that has a hash as an argument, below is a code example.

def funcUsingHash(input)
    input.each { |k,v|
        puts "%s=%s" % [k, v]
    }
end

funcUsingHash :a => 1, :b => 2, :c => 3

Find out more about hashes here http://www-users.math.umd.edu/~dcarrera/ruby/0.3/chp_03/hashes.html

Jamie
A: 

Maybe that *args can help you?

def meh(a, *args)
 puts a
 args.each {|x| y x}
end

Result of this method is

irb(main):005:0> meh(1,2,3,4)
1
--- 2
--- 3
--- 4
=> [2, 3, 4]

But i prefer this method in my scripts.

Kavu