tags:

views:

64

answers:

3

How can I declare a method with keyword arguments just like rails do. some examples may be

Person.find(:all, :conditions => "..."). 

How can I use symbols to create methods similar to the above?

I am very new to ruby. Thanks in advance!

A: 

Since Ruby is typed dynamically, just do :

def my_method(arg1, arg2)
  #things
end

example:

my_method(:test, {:somehash => "yay"})

or

my_method :test, :somehash => "yay"

or

my_method(:test, :somehash => "yay")
marcgg
+11  A: 

Ruby doesn't actually have keyword arguments. Rails is exploiting a feature of Ruby which lets you omit the braces around a hash. For example, with find, what we're really calling is:

Person.find(:all, { :conditions => "...", :offset => 10, :limit => 10 } )

But if the hash is the last argument of the method, you can leave out the braces and it will still be treated as a hash:

Person.find(:all, :conditions => "...", :offset => 10, :limit => 10)

You can use this in your own methods:

def explode(options)
    defaults = { :message => "Kabloooie!", :timer => 10, :count => 1 }
    options = defaults.merge(options)

    options[:count].times do
        sleep options[:timer]
        puts options[:message]
    end
end

And then call it:

explode :message => "Meh.", :count => 3
Samir Talwar
A: 

You just need to define a method where one of the parameters is a hash. It's actually pretty simple.

def method(arg1, params)
  name = params[:name]
  number = params[:number]

And then call it like:

method(arg1, :name => 'Eric', :number => 2)

Two notes:

  1. In Ruby, you don't need to surround the parameters hash in {} when you call the method in most cases, unless you have something complicated going on like passing multiple hashes. In that case, make sure you surround those parameters with {}
  2. Ruby is dynamically typed, so you don't need to say that params is a hash when you define the method.
saalon