1

I saw the code from here

Post.published.collect(&:views_count)

I guess it equals to

.collect { |p| p.views_count }

But I never saw this usage before, does this have a name? Where can I find more information about it?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Cheng
  • 4,816
  • 4
  • 41
  • 44

2 Answers2

2

This is actually a rather clever hack made it into ruby 1.9.

Basically, & in front of a variable in ruby coerces it into a proc. It does that by calling to_proc. Some clever fellow (first time I saw this was in _whys code, but I won't credit him cause I don't know if he came up with it) added a to_proc method to Symbol, that is essentially {|obj| obj.send self}.

There aren't many coercians in ruby, but it seems like all of them are mostly used to do hacks like this (like !! to coerce any type into a boolean)

Matt Briggs
  • 41,224
  • 16
  • 95
  • 126
  • 2
    Since the code snippet in question is using rails, it should be pointed out that `Symbol#to_proc` was in Active Support long before ruby 1.9, so you can use it in rails code without worrying about compatibility with ruby version. – sepp2k Oct 08 '10 at 06:11
2

It's a use of Symbol#to_proc. The & operator turns a Proc object into a block, and because Ruby 1.8.7 and newer implement Symbol#to_proc, it can be used with a symbol like :views_count. And yes, it's equivalent to {|p| p.views_count}.

Chuck
  • 234,037
  • 30
  • 302
  • 389