Skip to content

Instantly share code, notes, and snippets.

@ShiningRay
Created January 11, 2017 07:17
Show Gist options
  • Save ShiningRay/47bec50f1e21822a290109e19b10ba80 to your computer and use it in GitHub Desktop.
Save ShiningRay/47bec50f1e21822a290109e19b10ba80 to your computer and use it in GitHub Desktop.
def ... end syntax vs define_method
class Test
def initialize
@a = 100
end
a = 100
def test1
a
end
define_method('test2'){ a }
def test3
@a
end
end
t = Test.new
begin
puts t.test1 # def ... end does not establish closure, so cannot access free variable
rescue => e
puts e.inspect
end
puts t.test2 # define_method established a closure
require 'benchmark'
n = 500000
Benchmark.bm do |x|
x.report { n.times { t.test2 } }
x.report { n.times { t.test3 } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment