💎Ruby tip: ampersand(&) operator

Sebastien Auriault
Apr 2, 2022
Did you know that you can use the ampersand(&) operator with any method that requires a block for some convenient shortcuts?

Examples ⬇️
array = [nil, "", 2]
# To convert all values to strings
# instead of
array.map { |value| value.to_s }
# you can do
array.map(&:to_s)
# => ["", "", 2]

# Or to remove any nil or empty values
array.find_all(&:present?)
# => [2]

# The trick is that the ampersand(&)
# operator will convert to a proc
# and give it as a block. Converting
# a symbol to a proc will call the
# method on the param.
:to_s.to_proc.call(1)
# => "1"