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!
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) .
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.
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).
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.
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
Since Ruby 2.0, ruby does have keyword arguments.
def my_method(arg1, name: 'defaultName', number: 0)
puts arg1, name, number
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With