Common mistake for former Java developers: instance variables vs. class instance variables.
class Example
@foo = 1
@bar = 2
attr_accessor :foo
attr_accessor :bar
end
Example.new.foo #=> nil
Example.new.bar #=> nil
class Better
attr_accessor :foo
attr_accessor :bar
def initialize
@foo = 3
@bar = 4
end
end
Better.new.foo #=> 3
Better.new.bar #=> 4
Just remember that everything in Ruby is an object - including classes. So if all objects
can have instance variables, classes can too.
The way to tell whose instance variables you're talking about is by checking
the value of self
class WhoAmI
p self #=> WhoAmI
def initialize
p self #=> #<WhoAmI:0x25788>
end
def self.a_class_method
p self #=> WhoAmI
end
def an_instance_method
p self #=> #<WhoAmI:0x25788>
end
end