Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby keyword arguments of method

Tags:

ruby

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!

like image 887
Yang Avatar asked Mar 17 '10 14:03

Yang


People also ask

How do you pass keyword arguments in Ruby?

So when you want to pass keyword arguments, you should always use foo(k: expr) or foo(**expr) . If you want to accept keyword arguments, in principle you should always use def foo(k: default) or def foo(k:) or def foo(**kwargs) .

What is keyword parameter in Ruby?

Keyword Arguments (also called named parameters) are a feature of some programming languages, which gives the programmer the possibility to state the name of the parameter that is set in a function call. 02.04.2019.

How does * args work in Ruby?

In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).

How do you accept number of arguments in Ruby?

A method defined as def some_method(**args) can accept any number of key:value arguments. The args variable will be a hash of the passed in arguments.


2 Answers

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

Or call it without an argument, resulting in all default values being used:

explode
like image 129
Samir Talwar Avatar answered Oct 01 '22 15:10

Samir Talwar


Since Ruby 2.0, ruby does have keyword arguments.

def my_method(arg1, name: 'defaultName', number: 0)
  puts arg1, name, number
end
like image 29
Pieter Kuijpers Avatar answered Oct 01 '22 13:10

Pieter Kuijpers