secret
Last active

  • Download Gist
there_i_fixed_it.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 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

Haha. Evil.

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

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.