meaning of * in ruby function [duplicate] - ruby-on-rails

This question already has answers here:
What does the (unary) * operator do in this Ruby code?
(3 answers)
Closed 7 years ago.
I have a basic question about the mearning of * in a function call which I haven't been able to understand from online docs:
def self.new(*args, &block)
What does *args mean in the function call above?

consider a following method
def user(user_name)
puts user_name
end
so when you call
user("RPV")
Output:
RPV
=> nil
but what if you pass more then one argument like
user("RPV", "Marek")
it will give an error
wrong number of arguments (2 for 1)
To avoid this kind of error splat(*) operator is helpful
def user(*user_name)
puts user_name
end
and when you pass more than one argument it handles converts it in array
user("RPV", "Marek")
output:
RPV
Marek
nil
it makes user_name as an array
def user(user_name)
p user_name
end
user("RPV", "Marek")
output:
["RPV", "Marek"]
Hope you got the use of it.

It means you can pass any number of arguments that will be stored in args table inside of this method. Take a look: https://endofline.wordpress.com/2011/01/21/the-strange-ruby-splat/

Related

String to method name [duplicate]

This question already has answers here:
How to call methods dynamically based on their name? [duplicate]
(5 answers)
Closed 5 years ago.
I cant seem to follow this answer but maybe it's different from what I'm trying to achieve.
I have a string, that string can be different at time, I need to convert that string into a defined method name:
action = "get_name"
# The method
def get_name
puts "James"
end
# Calling the method
action # => undefined method `action' for main:Object
action can be any of my defined methods and the names are in a string format. Could I say action.to_method, you get what I mean ;)
I dont think I could say action.to_sym?
method(action).call
or
public_send(action)
Example:
method(action).call
#=> James
public_send(action)
#=> James
Be aware, though, that none of the above cares about the context, where was method originally defined, so both will call it in the context of the current object.

how to retrieve variable arguments in lua 5.2 [duplicate]

This question already has an answer here:
Parameter implicit "arg" in functions not work in Lua
(1 answer)
Closed 6 years ago.
The reference pages all say things like
function this(...)
end
However when I try to apply the supposed arg variable all I get is a nil reference. Any attempt I've made to capture the arguments results in a nil table. I've tried forcing a local tab = {...} and still get the nil reference. The closest I've managed to get to capturing the arguments is a select("#",...) which only returns the number of arguments. Whenever I try to capture this outside parameter declaration I get nothing but another error...
I've been thoroughly looking into this with no avail... any way I can accomplish this without forcibly passing a table?
The arg argument is for Lua 5.0 only. Since Lua 5.1, the vararg expression ... is used instead.
Try this:
function foo(...)
for k, v in ipairs{...} do
print(k, v)
end
end
foo('hello', 'world')

Meaning of -> shorthand in Ruby [duplicate]

This question already has answers here:
What do you call the -> operator in Ruby?
(3 answers)
Closed 8 years ago.
I was browsing Friendly_id gem code base and I found line with following assignment:
#defaults ||= ->(config) {config.use :reserved}
My questions are:
How do I interpret this line of code?
What does exactly -> do and what does it mean?
Is there any articles about it, how to use it?(Official Ruby documentation would be nice, I haven't found it)
Thank you for your help
This denotes the lambda. With this you are latching an anonymous function which takes a parameter config and computes a block using that variable.
The above expression can also be defined as:
#defaults ||= lambda {|config| config.use :reserved}
Proc is similar to lambda in Ruby, apart from few differences of return and break pattern. Proc can be called as a block saved as an object, while lambda is a method saved as an object. They find their roots in functional programming.
In short, a lambda is a named procedure, which can be saved as an object and can be called later.
inc = ->x{ x + 1 }
inc.call(3)
#=> 4
One common and interesting example of lambda is Rails Scope, where a method is simply assigned in name scope as lambda and can be later used as an action while ActiveRecord querying.

Can any one explain the use of '&' in this piece of ruby code? [duplicate]

This question already has answers here:
What does map(&:name) mean in Ruby?
(17 answers)
Closed 9 years ago.
Can any one explain the use of '&' in this piece of ruby code?
s.feature_addons.select(&:is_active?)
It means:
s.feature_addons.select { |addon| addon.is_active? }
The & calls to_proc on the object, and passes it as a block to the method.
class Symbol
def to_proc
Proc.new { |*args| args.shift.__send__(self, *args) }
end
end
U can define to_proc method in other classes: Examples
That's a shortcut for to_proc. For example, the code you provided is the equivalent of:
s.feature_addons.select {|addon| addon.is_active?}
Some old documentation for it can be found here:
http://apidock.com/rails/Symbol/to_proc (when it was provided by ActiveSupport)
It then became a part of Ruby core in 1.9
http://www.ruby-doc.org/core-1.9.3/Symbol.html
You can use this syntax as shorthand for methods to apply to an entire collection.
It is functionally the same as:
s.feature_addons.select { |a| a.is_active? }
You can use it with any collections, such as:
User.all.map(&:id)
etc

The meaning of `*` when using as a param(not like *arg, just *) [duplicate]

This question already has an answer here:
naked asterisk as parameter in method definition: def f(*)
(1 answer)
Closed 10 years ago.
When I was reading Rails code, I found this
def save(*)
create_or_update || raise(RecordNotSaved)
end
What does the * do? :O
I know what happens when we use it like *args, but in this case, it's just plain *.
ref https://github.com/rails/rails/blob/master/activerecord/lib/active_record/persistence.rb#L119
It means the same thing as it does when used with a parameter name: gobble up all the remaining arguments. Except, since there is no name to bind them to, the arguments are inaccessible. In other words: it takes any number of arguments but ignores them all.
Note that there actually is one way to use the arguments: when you call super without an argument list, the arguments get forwarded as-is to the superclass method.
In this specific case, save doesn't take any arguments. That's what happens with a naked splat. But, as you may be aware, calling save on an ActiveRecord model accepts options because this method gets overridden by ActiveRecord::Validations here:
https://github.com/rails/rails/blob/v3.1.3/activerecord/lib/active_record/validations.rb#L47
# The validation process on save can be skipped by passing <tt>:validate => false</tt>. The regular Base#save method is
# replaced with this when the validations module is mixed in, which it is by default.
def save(options={})
perform_validations(options) ? super : false
end

Resources