Skip to content

Instantly share code, notes, and snippets.

@sunaot
Created February 10, 2012 07:01
Show Gist options
  • Save sunaot/1787307 to your computer and use it in GitHub Desktop.
Save sunaot/1787307 to your computer and use it in GitHub Desktop.
Local static variable in Ruby
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