On Apr 8, 11:08 am, Christophe Decaux <[email protected]>
wrote:

> tasks.reject(&:new_record?).each do |task|

> I have no problem with the ".each do..." stuff, I guess that "reject" is 
> quite the opposite of find but I quite don't understand the "&:new_record?" 
> notation

> What is the purpose of the &
> Is it some sort of Ruby idiom
tophe

That is one of the few Rails idiom that was useful enough that it got
folded into Ruby. I think it is officially a part of 1.8.7 or 1.9 or
something.

Expanded out, it looks like this:

tasks.reject(&:new_record?).each { ... }
tasks.reject { |task| task.new_record? }.each { ... }

... meaning that the method new_record? is called for each of the task
passed in by reject. Reject itself will reject anything that evaluates
to true. In other words, that snippet of code filters out any tasks
that has not yet been saved to the database, then calls each on that.
So another application of that:

Tasks.all.map(&:name)
Tasks.all.map { |task| task.name }

Gives you a list of all of those task with their name, which I've
found pretty useful when playing around in the console.

For a more advanced discussion, the &:new_record? trick works because
it is essentially converting a Symbol into a Proc using Ruby duck
typing and to_proc, and the resulting Proc gets passed into the
reject.

Ho-Sheng Hsiao
http://hosheng.blogspot.com

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to