Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
Ruby often has a shortened entry for iterations:
[1, 2, 3].map(&:to_s)
It's the same as:
[1, 2, 3].map { |n| n.to_s }
But how exactly does the &:to_s design work?
Symbol#to_proc
The key idea is that Ruby allows you to convert characters to blocks using the to_proc method.
- The symbol :to_s represents the method name.
- The to_proc method converts a character to a block that calls the corresponding method on each collection element.
- The operator & informs Ruby that this block must be passed to the method (map, each, etc.).
You can see it like this:
s = :to_s p = s.to_proc [1, 2, 3].map(&p) # => ["1", "2", "3"]
That is &:to_s <TAG1> is a shortened entry for &(:to_s.to_proc)
If simple:
When we write &:to_s, he takes each element of the array i calls on him method to_s.
That is, this entry:
[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 itself "unfold" this character into a regular block.
Examples
1. Convert 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 the 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"]
How AI likes to write - Conclusion:
- &:method_name is a shortened entry for &(:method_name.to_proc).
- Ruby converts a character to a block using Symbol#to_proc, which calls a method on each element of the collection.
- This makes the code shorter and more readable.
The &:to_s or &:name design 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.