strs = ['foo', 'bar', 'baz']
# standard long form way
caps = strs.map { |str| str.upcase }
# short hand
caps = strs.map(&:upcase)
# The & takes any object and calls to_proc on it
# In the above example we're using a Symbol and not an object
# So the Symbol class's to_proc method returns a Proc,
# that given some object will send itself (the Symbol) as a message to that given object
# Using that explanation, the short hand is equivalent to:
caps = strs.map { |str| str.send(:upcase) }
2. Use existing method.rb
strs = ['foo', 'bar', 'baz']
def dramatise(word)
word += '!!'
end
strs.map(&method(:dramatise)) # => ["foo!!", "bar!!", "baz!!"]
3. Custom to_proc.rb
class Point
attr_accessor :x, :y
def initialize(x, y)
@x, @y = x, y
end
def self.to_proc
Proc.new do |args|
p args # => [1, 5], [4, 2]
new(*args) # => create new instance of the `Point` class and splat incoming Array into the constructor
end
end
end
[[1, 5], [4, 2]].map(&Point) # => [#<Point:0x007f87e983af40 @x=1, @y=5>, #<Point:0x007f87e983ace8 @x=4, @y=2>]