Skip to content

Instantly share code, notes, and snippets.

@sorah
Last active December 11, 2015 20:39
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 sorah/4657188 to your computer and use it in GitHub Desktop.
Save sorah/4657188 to your computer and use it in GitHub Desktop.
class Foo
# Defining class variable on Foo
@@bar = :alice
def hello
"Hello, #{@@bar}"
end
def bar=(x)
@@bar = x
end
end
foo_a = Foo.new
p foo_a.hello #=> "Hello, alice"
foo_b = Foo.new
# Foo#bar method replaces class variable @@bar.
foo_b.bar = :bob
# So, this effects to other instance of class Foo.
p foo_a.hello #=> "Hello, bob"
class Foo
@@bar = :alice
end
# Declare new class Bar inherits Foo
class Bar < Foo
# You can see superclass' class variable.
p @@bar #=> :alice
# Try to replace in subclass
@@bar = :john
end
class Foo
# Above line effects to its superclass, Foo!
p @@bar #=> :john
end
class Foo
end
class Bar < Foo
@@bar = :john
end
class Foo
# Similarly, you can replace subclass' class variable from superclass.
@@bar = :hello
end
class Bar
p @@bar #=> :hello
end
class Foo
class << self
def name
# At here `self` is class Foo, so, instance variable will be
# defined at class Foo.
@name ||= :alice # default value
end
def name=(x)
@name = x
end
end
end
p Foo.name #=> :alice
Foo.name = :bob
p Foo.name #=> :bob
p Foo.instance_variables #=> [:@name]
class Foo
class << self
def name
# At here `self` is class Foo, so, instance variable will be
# defined at class Foo.
@name ||= :alice # default value
end
def name=(x)
@name = x
end
end
end
class Bar < Foo
end
Foo.name = :bob
# Because :bob will be placed in Foo class' instance variable,
# so above line doesn't effect to class Bar.
p Bar.name #=> :alice
p Foo.name #=> :bob
class Foo
class << self
attr_accessor :name
end
end
Foo.name = :alice
p Foo.name #=> :alice
class Foo
class << self
attr_accessor :name
end
def hello
# look up using accessor declared on Foo class
"Hello, #{self.class.name}"
end
end
Foo.name = :alice
p Foo.new.hello #=> "Hello, alice"
class Foo
class << self
# Declare writer only
attr_writer :name
end
def hello
"Hello, #{name}"
end
private
def name
# Look up using Object#instance_variable_get.
self.class.instance_variable_get(:@name)
end
end
Foo.name = :alice
p Foo.new.hello #=> "Hello, alice"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment