Skip to content

Instantly share code, notes, and snippets.

@meltingice
Created May 15, 2014 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meltingice/ea3547c0023321786b7a to your computer and use it in GitHub Desktop.
Save meltingice/ea3547c0023321786b7a to your computer and use it in GitHub Desktop.
Ruby: Initializing class instance variables with default values for all subclasses
class ParentClass
@foo = "bar"
class << self
attr_accessor :foo
def inherited(subclass)
subclass.instance_variable_set :@foo, "bar"
super
end
end
end
class ChildClass < ParentClass
end
ParentClass.foo
#=> "bar"
ChildClass.foo
#=> "bar"
# Change the value for ChildClass only
ChildClass.foo = "look at me"
ChildClass.foo
#=> "look at me"
ParentClass.foo
#=> "bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment