Possible Duplicate:
What does map(&:name) mean in Ruby?
Ruby/Ruby on Rails ampersand colon shortcut
For example,
contacts.sort_by(&:first_name).
I understand what this does, but I dont understand the &: notations, what does that mean, is it a symbol(:) with a block (&)? Where can I read more about it?
When &
used before Proc object in method invocation, it treats the Proc as if it was an ordinary block following the invocation.
When &
used before other type of object (symbol :first_name
in your case) in method invocation, it tries to call to_proc on this object and if it does not have to_proc method you will get TypeError
.
Generally &:first_name
is the same as &:first_name.to_proc
.
Symbol#to_proc Returns a Proc object which respond to the given method by sym.
:first_name.to_proc
will return Proc that looks like this:
proc { |obj, *args, &block| obj.first_name(*args, &block) }
this Proc invokes method specified by original symbol on the object passes as the first parameter and pass all the rest parameters + block as this method arguments.
One more example:
> p = :each.to_proc
=> #<Proc:0x00000001bc28b0>
> p.call([1,2,3]) { |item| puts item+1 }
2
3
4
=> [1, 2, 3]
It is same with contacts.sort_by {|o| o.first_name}
It returns a Proc object which respond to the given method by sym.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With