Skip to content

Instantly share code, notes, and snippets.

@alindeman
Last active December 18, 2015 00:59
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alindeman/ad8b06b796beaa9b60ea to your computer and use it in GitHub Desktop.
Save alindeman/ad8b06b796beaa9b60ea to your computer and use it in GitHub Desktop.
# This is a joke! You'd be crazy to use it.
#
# But, isn't it interesting?
#
# Symbol#to_proc normally returns something like proc { |o| o.send(self) }
#
# This code hacks it such that if a method exists in the *caller's* binding,
# that method is invoked instead.
#
# Ruby 2.0 only (for debug_inspector)
require 'debug_inspector'
module SymbolExtensions
def to_proc
method = nil
RubyVM::DebugInspector.open do |i|
method = eval "method(:#{self}) rescue nil", i.frame_binding(2)
end
method ? method.to_proc : super
end
end
Symbol.send :prepend, SymbolExtensions
["Hello World", "Ouch", "Fizzbuzz"].each(&:puts) # Method#to_proc
p ["1", "2", "3"].map(&:to_i) # Symbol#to_proc
@mkdynamic
Copy link

Haha. Evil.

I always got tired of writing this, no longer :)

["Hello World", "Ouch", "Fizzbuzz"].each(&method(:puts))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment