public
Last active

Rewrite block source with instance eval

  • Download Gist
fail.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
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
success.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.