Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
In Ruby, a shorthand notation for iterations is often encountered:
[1, 2, 3].map(&:to_s)
This is the same as:
[1, 2, 3].map { |n| n.to_s }
But how exactly does the &:to_s construct work?
Symbol#to_proc
The key idea is that Ruby allows converting symbols to blocks using the to_proc method.
- The symbol :to_s represents the name of the method.
- The to_proc method converts the symbol to a block that calls the corresponding method on each element of the collection.
- The & operator tells Ruby that this block should be passed to a method (map, each, etc.).
This can be seen like this:
s = :to_s p = s.to_proc [1, 2, 3].map(&p) # => ["1", "2", "3"]
That is, &:to_s is a shorthand for &(:to_s.to_proc)
Simply put:
When we write &:to_s, it takes each element of the array and calls the to_s method on it.
So this notation:
[1, 2, 3].map(&:to_s)
means the same as:
[1, 2, 3].map { |n| n.to_s }
&:to_s is just a short way to say "call the to_s method on each element." Ruby "expands" this symbol into a regular block.
Examples
1. Converting numbers to strings
numbers = [1, 2, 3] strings = numbers.map(&:to_s) # => ["1", "2", "3"]
2. Calling other methods
words = ["hello", "world"] capitalized = words.map(&:upcase) # => ["HELLO", "WORLD"]
3. Calling object’s own methods
class Person
attr_reader :name
def initialize(name)
@name = name
end
end
people = [Person.new("Alice"), Person.new("Bob")]
names = people.map(&:name)
# => ["Alice", "Bob"]
As AI likes to write - Conclusion:
- &:method_name is a shorthand for &(:method_name.to_proc).
- Ruby converts a symbol to a block using Symbol#to_proc, which calls the method on each element of the collection.
- This makes the code shorter and more readable.
The &:to_s or &:name construct is very convenient for collections when you need to call one method on all elements.
This post doesn't have any additions from the author yet.