Skip to content

Instantly share code, notes, and snippets.

@jordansissel
Created May 15, 2011 21:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordansissel/973554 to your computer and use it in GitHub Desktop.
Save jordansissel/973554 to your computer and use it in GitHub Desktop.
Understanding Ruby's &:foo shortcut

Example usage of the '&:foo' syntax

# You can do this:
p ["hello", "world"].collect(&:upcase)

Output:

["HELLO", "WORLD"]

What just happeend? What does '&:upcase' mean?

We can see that it called "hello".upcase, etc, for each element in the array.

What really is goign on though? We can play with it by capturing the proc generated by '&:upcase':

def getmethod(&block)
  return block
end

func = getmethod(&:upcase)
p func

output (from irb):

#<Proc:0x00007fe1ab12ad60@(irb):29>

What can we do with that:

func.call("hello there!")

Output:

"HELLO THERE!"

So passing &:foo to a method as the 'block' seems to generate a method that calls the 'foo' method on the first argument.

And that is exactly what .collect(&:upcase) does in the example at the top.

@GreenThumbsUp
Copy link

Thanks for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment