Skip to content

Instantly share code, notes, and snippets.

@nickh
Created December 7, 2011 17:50
Show Gist options
  • Select an option

  • Save nickh/1443805 to your computer and use it in GitHub Desktop.

Select an option

Save nickh/1443805 to your computer and use it in GitHub Desktop.
Class instance variables

Things and stuff

ruby-1.9.3-preview1 :015 > t1 = Thing.new
 => #<Thing:0x007fcaf104fa60> 
ruby-1.9.3-preview1 :016 > t2 = Thing.new
 => #<Thing:0x007fcaf2001008> 
ruby-1.9.3-preview1 :017 > t2.cache_some_stuff(:foo, 1)
 => 1 
ruby-1.9.3-preview1 :018 > Thing.instance_variable_get('@cached_stuff')
 => {:foo=>1} 
ruby-1.9.3-preview1 :019 > t1.cached_stuff
 => {:foo=>1} 
ruby-1.9.3-preview1 :020 > t1.cached_stuff[:bar] = 2
 => 2 
ruby-1.9.3-preview1 :021 > t2.cached_stuff[:bar]
 => 2 
class Thing
def self.cached_stuff
@cached_stuff ||= {}
end
def cached_stuff
self.class.cached_stuff
end
def cache_some_stuff(k, v)
cached_stuff[k] = v
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment