Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does &: mean in ruby, is it a block mixed with a symbol? [duplicate]

Tags:

ruby

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?

like image 436
Kamilski81 Avatar asked Feb 08 '12 05:02

Kamilski81


2 Answers

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]
like image 88
Aliaksei Kliuchnikau Avatar answered Oct 10 '22 22:10

Aliaksei Kliuchnikau


It is same with contacts.sort_by {|o| o.first_name}

It returns a Proc object which respond to the given method by sym.

like image 28
xdazz Avatar answered Oct 10 '22 23:10

xdazz