In ruby web define parameters for a method.
def para_check(para1, para2, para3 .... )
end
How does activerecord .where is defined so that it accepts dynamic parameters ?
I went though few blogs/websites but could not find useful resources.
In Ruby you can prefix the parameter with a splat (*) to define methods that accept any number of positional arguments:
def foo(*x)
x
end
foo(1,2,3) == [1,2,3] # true
This is also known as a variadic function. As you can see this creates a array from the list of arguments.
You can also combine numbered and positional arguments and a splat:
foo(bar, *args)
[bar, args]
end
foo(1, 'a', 'b') == [1, ['a','b']] # true
This makes the method require one argument but allows an infinate number of arguments.
The ActiveRecord::QueryMethods#where method accepts both positional and keyword arguments:
where('foo = :x OR bar = :y', x: 1, x: 2)
Starting with Ruby 2.0 you can do this with:
def foo(*args, **kwargs)
[args, kwargs]
end
foo(1, 2, 3, bar: 'baz') == [[1, 2, 3], { bar: 'baz' }] ## true
Previously you had to use various hacky solutions with array parameters and and optional hash parameter. You can still find these in the Rails source code and in a lot of other code written before Ruby 2.0.
There are a few ways to do this. For starters you could accept a hash or array as parameter.
So if you expect a Hash, that is what where does, you can just write
def para_check(params)
params.each do |param_name, param_value|
# do something with the params
end
end
and then you can write:
para_check(para1: "X", para2: "Y", para5: "Z")
An alternative, in this case maybe, if you need to specify a list/array of parameters, you can also define your method as follows:
def para_check(*params)
params.each do |param_name|
# do something with param_name
end
end
(the '*'-operator is called the splat-operator)
and then you call your method as follows
para_check(:para1, :para2, :para4)
Related
I have an already existing method in my concern file, which has following number parameters define. For ex
module MyMethods
def close_open_tasks(param_1, param_2, param_3 = nil)
p param_1
p param_2
p param_3
end
end
But I am trying to add one more new optional parameter at the end param_4 in the above method.
Lets say I am including this module from an api and calling it from there.
When I call the following
close_open_tasks("test1","test2","test4")
"test4" is getting assigned to param_3 arg. How can I make it assign to param_4? Since both param_3 and param_4 are optional parameters its getting trickier with order.
You can use keywords arguments
module MyMethods
def close_open_tasks(param_1:, param_2:, param_3: nil, params_4: nil)
p param_1
p param_2
p param_3
end
end
and call it like this
close_open_tasks(param_1: "test1", param_2: "test2", param_4: "test4")
If your method has more then two positional arguments or there is no obvious order to the arguments you should define them as keyword arguments.
def close_open_tasks(foo, bar:, baz:) # required
def close_open_tasks(foo, bar: 3, baz: nil) # with defaults
If your method should actually take a list of arguments of any length you can use a splat:
def close_open_tasks(*tasks)
tasks.map do
task.close
end
end
close_open_tasks(task1, task2)
The equivilent for keyword arguments is the double splat:
def close_open_tasks(foo, bar: 3, baz: nil, **opts)
Which will provide a opts hash containing the additional keyword args.
When dealing with a method that takes a known number of arguments plus an options hash, is there any difference/advantage of capturing the options in a double splat?
consider
def method_a(a, **options)
puts a
puts options
end
vs
def method_b(a, options = {})
puts a
puts options
end
Are the two equivalent? I think method_b is more readable but still I see a lot of code going with method_a.
Is there a reason to use double splat for options when the regular (non options) arguments are captured without a splat?
Well it depends what you mean by "known number of arguments", specifically for the situation when you have keyword arguments plus any number of other keyword args, for example:
def foo(i, keyword_1: "default", **other_keywords)
end
I can call this as
foo(6, keyword_1: "asd", other: "keyword")
And {other: "keyword"} will be contained in other_keywords while keyword_1 can be accessed directly as a local variable.
Without the ** splat operator this behavior is more cumbersome to implement, something like this:
def foo(i, opts={})
keyword_1 = opts.delete(:keyword_1) || "default"
# now `opts` is the same as `other_keywords`
end
Another difference is the fact that the ** version captures rest keyword arguments. Keyword arguments are represented by symbols, resulting in the following behaviour:
def a(**options)
options
end
def b(options = {})
options
end
a(a: 1) #=> {:a=>1}
a('a' => 1) #=> ArgumentError (wrong number of arguments (given 1, expected 0))
b(a: 1) #=> {:a=>1}
b('a' => 1) #=> {"a"=>1}
def c(hash_options = {}, **keyword_options)
[hash_options, keyword_options]
end
# symbols are extracted and used as rest keyword arguments
c('a' => 1, b: 2, 'c' => 3, d: 4) #=> [{"a"=>1, "c"=>3}, {:b=>2, :d=>4}]
I have some code that looks like this:
if args
eval("super(#{args.join(',')})")
else
super
end
twice in a method. I'd like to move it so that my code looks more like:
def special_method
if a
some_block do
call_super(args, super_method)
end
else
call_super(args, super_method)
end
end
def call_super(args, super_method)
if args
eval("super(#{args.join(',')})")
else
super
end
end
I need to have a reference to the super I want to call (super special_method), since if I just create a method call_super and call super, it calls call_super on the superclass instead.
Does any of this make sense? x_x
It makes sense except for why you would ever need it. super already passes any parameters that the current method receives. super() passes no params. super(*args) passes any params in args, or no params if args is [] or nil.
If you actually want to do what your code currently does (pass args if they are non-nil, but current method's params if not) and not what I think you wanted, you can write args ? super(*args) : super as a short alternative (you can't put this in another method since it wouldn't know what the current parameters are).
(Also, you will find that in 99% of cases you think eval is the answer, there is a better answer.)
EDIT in response to the comment:
if args is ['testing', 1], then super(args) will pass one parameter that is an array; super(*args) passes two parameters (a string and an integer):
# a module
module Foo
def special_method
# multiple arguments in `args`
args = ['testing', 1]
super(*args)
end
end
class Bar
# fixed number of arguments (without splats):
def special_method(first, second)
puts "First parameter: #{first}"
puts "Second parameter: #{second}"
end
end
# subclass that includes the module
class Baz < Bar
include Foo
end
Baz.new.special_method
# First parameter: testing
# Second parameter: 1
(Note that "multiple arguments in *args" does not make sense, as *args is not a variable, args is).
I think one of the reasons for the confusion is the fact that splat has two different but related roles. In method definitions, they collect arguments into an array. Everywhere else, they distribute an array to an argument list.
require 'pp'
def foo(*args)
pp args
end
foo([1, 2]) # all the parameters (namely, the one) collected into `args`
# [[1, 2]]
foo(1, 2) # all the parameters (the two) collected into `args`
# [1, 2]
foo(*[1, 2]) # distribute `[1, 2]` to two parameters; collect both into `args`
# [1, 2]
def foo(args)
pp args
end
foo([1, 2]) # all the parameters (the one that exists) passed as-is
# [1, 2]
foo(1, 2) # all the parameters (the two) passed as-is, but method expects one
# ArgumentError: wrong number of arguments (2 for 1)
foo(*[1, 2]) # distribute `[1, 2]` to two parameters, but method expects one
# ArgumentError: wrong number of arguments (2 for 1)
I've a method like:
def method (a=[],b=[])
...
end
I am calling this method with variables like this:
method(h[0].values_at("value"), h[1].values_at("value"))
where h[0] and h[1] are hashes. It works fine.
I dont know if h[1] is going to be there in the next run, so it's giving me error if hash h[1] is not there.
How can I modify it so it makes the call dynamically depending on whether h[0], h[1] are there or not, and call the method with the correct number of parameters.
Hope I understood your problem right:
method(h[0].values_at("value"),
h[1] ? h[1].values_at("value") : []
)
Your problem: if h[1]does not exist, h[1].values_at will raise an exception. So you have to test first, if the value is available. In the code snipllet above I used a ternary operator.
An extended version would be:
par2 = []
par2 = h[1].values_at("value") if h[1]
method(h[0].values_at("value"),
par2
)
With my solution you don't need the default values in the method definition.
In your comment you extended your question.
With four parameters you could use it like this:
def method(p1,p2,p3,p4)
#...
end
method(
h[0] ? h[0].values_at("value") : [],
h[1] ? h[1].values_at("value") : [],
h[2] ? h[2].values_at("value") : [],
h[3] ? h[3].values_at("value") : [],
)
But I would recommend a more generic version:
def method(*pars)
#pars is an Array with all values (including empty arrays.
#The next check make only sense, if you need exactly 4 values.
raise "Expected 4 values, get #{pars.size}" unless pars.size == 4
end
method( *(h.map{|i|i.values_at("x")})
And another - probably not so good - idea:
Extend nil (the result of h[1] if h has not this element) to return [] for values_at:
class NilClass
def values_at(x)
[]
end
end
The simplest way to do exactly what you ask would be:
if h[1]
method(h[0].values_at("x"), h[1].values_at("x"))
else
method(h[0].values_at("x"))
end
Another idea is to put a default hash in the case where h[1] is nil
method(h[0].values_at("x"), (h[1]||{}).values_at("x") )
If you are sure h never has more than 2 items, you can do:
method *(h.map{|i|i.values_at("x")})
If you use Ruby On Rails you are able to execute try method:
method(h[0].values_at("value"), h[1].try(:values_at, 'value') || [])
Examples for method try:
nil.try('[]', :x) # => nil
{:x => 't'}.try('[]', :x) # => 't'
You can change the function signature to accept variable arguments.
def foo(*args)
options = args.extract_options!
p options
p args
end
Invocation without parameters
foo()
{}
[]
Invocation with 2 parameters
foo(1, 2)
{}
[1, 2]
Invocation with 3 parameters
foo(1, 2, 3)
{}
[1, 2, 3]
Invocation with 3 parameters and an option hash
foo(1, 2, 3, :debug => true)
{:debug=>true}
[1, 2, 3]
I am using Ruby on Rails 3 and I would like to know what means the presence of a * operator near a function argument and to understand its usages in others scenarios.
Example scenario (this method was from the Ruby on Rails 3 framework):
def find(*args)
return to_a.find { |*block_args| yield(*block_args) } if block_given?
options = args.extract_options!
if options.present?
apply_finder_options(options).find(*args)
else
case args.first
when :first, :last, :all
send(args.first)
else
find_with_ids(*args)
end
end
end
This is the splat operator, which comes from ruby (and is thus not rails specific). It can be applied in two ways depending on where it is used:
to "pack" a number of arguments into an array
to split up an array into an argument list
In your function, you see the splat operator used in the function definition. The result is that the function accepts any number of arguments. The complete argument list will be put into args as an array.
def foo(*args)
args.each_with_index{ |arg, i| puts "#{i+1}. #{arg}" }
end
foo("a", "b", "c")
# 1. a <== this is the output
# 2. b
# 3. c
The second variant would be when you consider the following method:
def bar(a, b, c)
a + b + c
end
It requires exactly three arguments. You can now call this method like follows
my_array = [1, 2, 3]
bar(*my_array)
# returns 6
The splat applied in this case to the array will split it and pass each element of the array as an individual parameter to the method. You could do the same even by calling foo:
foo(*my_array)
# 1. 1 <== this is the output
# 2. 2
# 3. 3
As you can see in your example method, these rules do apply to block parameters in the same way.
This is a splat argument, which basically means that any 'extra' arguments passed to the method will all be assigned to *args.