Created
September 9, 2013 17:55
-
-
Save diego-aslz/6499149 to your computer and use it in GitHub Desktop.
How does the `&:name` parameter work?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| cities = City.all | |
| cities.map(&:name) # ['City 1', 'City 2'] |
Author
It is an alias for something like
cities = City.all
cities.map { |city| city.name }In this case, it will map your cities list to list of the city names.
protip:
[1, 3, 10, 20, 34, 54, 60].inject(:+)
Author
Right, but I'd like to understand how to use the '&' parameter. Is it interpreted as a block, maybe?
& is some kind of alias to a Proc. It's in the Ruby language itself, by the way.
class City
attr_accessor :name
def initialize(name)
@name = name
end
end
puts [City.new('City 1'), City.new('City 2')].map(&:name)
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.
Author
Thanks.
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" #=> 4Nice! Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How does it work? What is the '&' char for?