Created
February 10, 2012 07:01
-
-
Save sunaot/1787307 to your computer and use it in GitHub Desktop.
Local static variable in Ruby
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
module Static | |
cache = "" | |
klass = class<<self; self; end | |
klass.send(:define_method, :foo) do | |
lambda {|s| cache += s; cache } | |
end | |
def self.out_of_scope | |
cache | |
rescue | |
"you cannot see cache" | |
end | |
end | |
f = Static.foo | |
f.call "hello" | |
f.call ", " | |
f.call "world" | |
module Say | |
def self.hello | |
f = Static.foo | |
f.call("!") | |
end | |
end | |
puts Say.hello #=> "hello, world!" | |
puts Static.out_of_scope #=> "you cannot see cache" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment