Ruby Method Double Splat vs Hash - ruby-on-rails

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}]

Related

Order of parameters in ruby method

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.

How does rails activerecord where clause accepts dynamic parameter?

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)

Ruby: Pass super into another method to execute conditionally

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)

How to get a list of the arguments a method is called with

How do I get a list of the arguments passed to a method, preferably one that I can iterate through?
For example something like
def foo(a,b,c)
puts args.inspect
end
foo(1,2,3)
=> [1,2,3]
?
Thanks!
You can always define a method that takes an arbitrary number of arguments:
def foo(*args)
puts args.inspect
end
This does exactly what you want, but only works on methods defined in such a manner.
The *args notation means "zero or more arguments" in this context. The opposite of this is the splat operator which expands them back into a list, useful for calling other methods.
As a note, the *-optional arguments must come last in the list of arguments.
If you define your method as you specified, you'll always have 3 args, or the method call is invalid. So "all the args" is already defined for you. So you would just change your method to:
def foo(a,b,c)
[a, b, c]
end
To define a method that can be called with any args (and to then access those args) you can do something like this:
def foo(*args)
args
end
What the * does is put all args after that point into an array.
As others pointed out you can use the splat operator (*) for achieving what you want. If you don't like that, you can use the fact that Ruby methods can take a hash as last argument with nicer syntax.
def foo(args)
raise ArgumentError if args.keys.any? { |arg| arg.nil? || !arg.kind_of?(Integer) }
end
puts foo(:a => 1, :b => 2, :c => "a") # raise an ArgumentError
To access the arguments inside the method you have to use args[:a] etc.

What does the * (asterisk) symbol do near a function argument and how to use that in others scenarios?

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.

Resources