what does this syntax mean in Ruby? .. tasks.all?(&:complete?) [duplicate] - ruby-on-rails

This question already has answers here:
What does map(&:name) mean in Ruby?
(17 answers)
Closed 3 years ago.
I'm walking through the example project in the Rails 5 Test Prescriptions - Build a Healthy Codebase (published date: 2018) book and encountering this method:
#pages 29-30 of the book
class Project
.
.
def done?
tasks.all?(&:complete?) #only this line confused me, especially the `&` part
end
end
the syntax looks really strange to me since I just learned Ruby & Rails for more than one month..any hints just for pointing me to where I should read would be really appreciated

& is for passing block to method as a block (also used the other way in parameter list to make implicit block a parameter), it implicitly calls to_proc on passed object.
Symbol#to_proc for :symbol makes a proc{|param| param.symbol }
So your code is equvalent to tasks.all?{|task| task.complete? }

Related

Is there any opposite of include? method in Ruby? [duplicate]

This question already has answers here:
Ruby: Is there an opposite of include? for Ruby Arrays?
(13 answers)
Closed 4 years ago.
I have a question: Is there any opposite method of .include? I know with unless, but I want to do it with if, can I? I tried with unless:
unless variable.include?("something")
#..
end
I want to do it with if, can I? I know .!include? but it didn't work(i don't really know if this method exists, but I saw it in this forum).
if !variable.include?("something")
in plain Ruby
if variable.exclude?("something")
in Rails

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

Will my "in?" monkey patch cause issues? [duplicate]

This question already has answers here:
Is there an inverse 'member?' method in ruby?
(5 answers)
Closed 8 years ago.
So a fairly common pattern I've run up against is something like this:
[:offer, :message].include? message.message_type
The inversion of wording there messes me up. So I wrote this little monkey patch for Symbol in specific.
def in? *scope
scope.include? self
end
So now I can do the previous this way:
message.message_type.in? :offer, :message
This works fine and I'm happy with it, but occasionally I need similar functionality for other objects. Model objects in Rails apps being the most common case but strings occasionally, etc.
What kind of issues would I run into if I monkey patched this directly into Object?
Rails (ActiveSupport) already patches Object with this method. Here is the documentation: http://api.rubyonrails.org/classes/Object.html#method-i-in-3F.
Returns true if this object is included in the argument. Argument must be any object which responds to #include?. Usage:
characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true
This will throw an ArgumentError if the argument doesn’t respond to #include?.

What is the underlying code for TableA.create(TableB.all.map(&:attributes))? [duplicate]

This question already has an answer here:
What does map(&:name) do in this Ruby code?
(1 answer)
Closed 8 years ago.
For example, if I use rename method in mongo ruby driver, I can check the code here
What exactly is happening when I am using map(&:attributes)?
I think this means tags.map(&:attributes.to_proc).join(' '), but I am not sure why I am getting "undefined method `each_pair' for Arrayxxxxx" error with this command:
TableA.create(TableB.all.map(&:attributes))
Any insight will be appreciated
map returns an array of whatever is returned by the method call.
so
TableB.all.map(&:attributes)
is basically an array of
[TableB.all[0].attributes,TableB.all[1].attributes,TableB.all[2].attributes,...]
Do you want something like
TableB.all.map(&:attributes).each do |attr|
TableA.create(attr)
end

Resources