Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active January 29, 2016 08:51
Show Gist options
  • Save Integralist/11206577 to your computer and use it in GitHub Desktop.
Save Integralist/11206577 to your computer and use it in GitHub Desktop.
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()`)
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) }
strs = ['foo', 'bar', 'baz']
def dramatise(word)
word += '!!'
end
strs.map(&method(:dramatise)) # => ["foo!!", "bar!!", "baz!!"]
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>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment