Created
January 11, 2017 07:17
-
-
Save ShiningRay/47bec50f1e21822a290109e19b10ba80 to your computer and use it in GitHub Desktop.
def ... end syntax vs define_method
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
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