4

Possible Duplicate:
What does map(&:name) mean in Ruby?

What does the &:valid? found in the each mean? I've seen .each do |r| or whatever, but not sure how this one works?

Community
  • 1
  • 1
Joshua F. Rountree
  • 1,462
  • 2
  • 14
  • 30
  • 1
    I think it's just a shorthand for `temps.collect{ |t| t.valid == true}` – Joseph Le Brech Mar 29 '12 at 13:52
  • You can read more about it [here](http://kconrails.com/2010/12/01/ruby-enumerable-primer-part-2-unary-ampersand-operator/) – Christian Mar 29 '12 at 14:03
  • 1
    This is a duplicate of no less than 17 other questions that have already been asked and answered here on StackOverflow: [Understanding \[ClassOne, ClassTwo\].each\(&:my_method\)](http://StackOverflow.Com/q/99318/), [What does `map(&:name)` mean in Ruby?](http://StackOverflow.Com/q/1217088/), [What exactly is `&:capitalize` in Ruby?](http://StackOverflow.Com/q/1792683/), [Ruby/Ruby on Rails ampersand colon shortcut](http://StackOverflow.Com/q/1961030/), [Ruby : `&:symbol` syntax](http://StackOverflow.Com/q/2096975/), … – Jörg W Mittag Mar 29 '12 at 14:53
  • … [What is this `&:last` Ruby Construct Called?](http://StackOverflow.Com/q/2211751/), [What do you call the `&:` operator in Ruby?](http://StackOverflow.Com/q/2259775/), [What does `map(&:name)` do in this Ruby code?](http://StackOverflow.Com/q/2388337/), [What are `:+` and `&+` in ruby?](http://StackOverflow.Com/q/2697024/), [`&:views_count` in `Post.published.collect(&:views_count)`](http://StackOverflow.Com/q/3888044/), [Ruby Proc Syntax](http://StackOverflow.Com/q/4512587/), [How does “`(1..4).inject(&:+)`” work in Ruby](http://StackOverflow.Com/q/5003257/), … – Jörg W Mittag Mar 29 '12 at 14:54
  • … [What does following statement `&:property` ?](http://StackOverflow.Com/q/5620411/), [What does the `&` mean in the following ruby syntax?](http://StackOverflow.Com/q/5952175/), [Why would one use the unary operator on a property in ruby? i.e `&:first`](http://StackOverflow.Com/q/6289084/), [how does `Array#map` have parameter to do something like this?](http://StackOverflow.Com/q/6716629/), [what does `&:` mean in ruby, is it a block mixed with a symbol?](http://StackOverflow.Com/q/9188362/), and [what is the functionality of “`&:`” operator in ruby?](http://StackOverflow.Com/q/9429819/). – Jörg W Mittag Mar 29 '12 at 14:54
  • Okay... well obviously since &:valid? was unique to this and I didn't quite understand the code - the "similar questions" query did not return any relevant questions you are suggesting. – Joshua F. Rountree Mar 29 '12 at 15:03

2 Answers2

12

The & is called the to_proc operator. It expands the symbol (:valid?) into a Proc. So your example is equivalent to:

temps.each { |t| t.valid? }
simonmenke
  • 2,819
  • 19
  • 28
4

&:symbol is a shorthand for symbol to proc.

Here's a good blog post on it. http://blog.hasmanythrough.com/2006/3/7/symbol-to-proc-shorthand

Joe Pym
  • 1,826
  • 12
  • 23