Last active
December 20, 2015 14:39
-
-
Save bootstraponline/6148819 to your computer and use it in GitHub Desktop.
Rewrite block source with instance eval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'method_source' | |
ary = [] | |
class Test | |
def self.run &block | |
define_method :run_method do | |
# https://www.ruby-forum.com/topic/4416134#1117671 | |
eval %(ary << 1; puts 'complete'), block.binding | |
end | |
Test.new.run_method | |
end | |
end | |
Test.run do | |
ary << 1 | |
puts 'complete' | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ary = [] | |
class Test | |
def self.run &block | |
define_method :run_method do | |
# ary is in scope | |
self.instance_eval &block | |
end | |
Test.new.run_method | |
end | |
end | |
Test.run do | |
ary << 1 | |
puts 'complete' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment