0

If there is a statement like this a.map{|x| x.foo}, I can omit x variable like this map(&:foo).

I'm wondering if there is a name for this behavior. Without name I couldn't looking for similar behavior in other language.

Does somebody know about this?

ironsand
  • 14,329
  • 17
  • 83
  • 176
  • This seems like syntax that is specific to Ruby. In C#, the unabbreviated syntax is called a Lambda Expression, but there's no way to abbreviate it, and a Lambda is something else in Ruby. – Robert Harvey Apr 03 '14 at 21:40
  • It's a form of type coercion. In this case, it tries to convert the given object to a proc by calling `to_proc` on it. – Zach Kemp Apr 03 '14 at 21:45

1 Answers1

4

It's often called "Symbol to Proc". It was originally a hack in Rails, then was incorporated and optimized, in Ruby.

You won't find a similar thing in other languages, unless they also implement Ruby's Symbol type. Symbols aren't the same as constants, but if you imagine a constant that points to a function, maybe a closure in other languages, then you'd be close to its behavior.

"What does map(&:name) mean in Ruby?" is a good discussion about it, along with an example of how it's implemented. Also check out the related posts on the righthand side of that page.

Also, there's "What do you call the &: operator in Ruby?".

Community
  • 1
  • 1
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • I was just about to post that link. I love ruby syntactic sugar but it definitely can be confusing sometime. Excellent answer – engineersmnky Apr 03 '14 at 21:51
  • If you find that confusing wait until you're debugging dynamically-created methods based on fieldnames in a database, or multi-threaded apps. – the Tin Man Apr 03 '14 at 21:53