Hacker News new | ask | show | jobs
by irishsultan 2637 days ago
It's not

  users.map{&:name}
but

  users.map(&:name)

The &something syntax to pass on a block is very old syntax to allow passing on a block that is reified as a Proc, it mirrors the syntax used to receive a block (if you don't want to use, or can't use yield, for example because you need to pass on the block to another method).

e.g.

   def apply_to_all(&callback)
     @all.each(&callback)
   end
or

   def initialize(a, b, c, &block)
     @a = a
     super(b, c, &block)
   end

The only thing that &:symbol adds is that it defines to_proc on Symbols to create a Proc object that sends the symbol to it's first parameter, you could define it yourself if Ruby didn't already, and in fact it was first defined by users of Ruby before it became part of Ruby core.

Definition:

   class Symbol
     def to_proc
        return Proc.new {|receiver| receiver.send(self)}
     end
   end
This definition allows `["1", "2", 3].map(&:to_i)` to work in Ruby 1.8.6, which otherwise doesn't support it.
1 comments

Thanks. As you see I dislike that syntax so much that I never learned how to write it. It's not something I'll actively use.