The &:present? syntax in Ruby is a shorthand that combines two different Ruby features:
- The & operator, which converts a proc/lambda to a block or vice versa
- Symbol to proc conversion using the :method_name syntax
Here's what happens step by step:
- :present? is a Symbol representing the method name "present?"
- Ruby has a feature where a Symbol can be converted to a proc using Symbol#to_proc. So :present?.to_proc creates a proc that calls the present? method on whatever object is passed to it.
- The & operator then converts this proc into a block that can be used with methods like all?, any?, map, etc.
[a, b, c, d, e].all?(&:present?)
It's equivalent to:
[a, b, c, d, e].all? { |item| item.present? }
names = users.map(&:name) # Same as: users.map { |user| user.name }
active_users = users.select(&:active?) # Same as: users.select { |user| user.active? }