« Back to Index

Ruby: Symbol class to_proc and custom class object to_proc (see also https://gist.github.com/Integralist/8079e79c5eb4e7b88183 to see how to use & with method())

View original Gist on GitHub

1. Typical Example.rb

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>]