Skip to content

Instantly share code, notes, and snippets.

@diego-aslz
Created September 9, 2013 17:55
Show Gist options
  • Select an option

  • Save diego-aslz/6499149 to your computer and use it in GitHub Desktop.

Select an option

Save diego-aslz/6499149 to your computer and use it in GitHub Desktop.
How does the `&:name` parameter work?
cities = City.all
cities.map(&:name) # ['City 1', 'City 2']
@diego-aslz
Copy link
Author

I found the answer here:

If the last argument to a method is preceded by an ampersand, Ruby assumes that it is a Proc object.
It removes it from the parameter list, converts the Proc object into a block, and associates it with the method.

@diego-aslz
Copy link
Author

Thanks.

@diego-aslz
Copy link
Author

It uses the to_proc method, so it's possible to do this:

class Greeter
  def to_proc
    lambda { "hello world" }
  end
end

def greet
  yield
end

greet &Greeter.new #=> "hello world"

And this:

class String
  def to_proc
    text = self
    lambda { eval text }
  end
end

instance_eval &"2 + 2" #=> 4

@caarlos0
Copy link

caarlos0 commented Sep 9, 2013

Nice! Thanks

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