Where is the attribute @color defined here? Presumably the assignment in the constructor? If this is the case, what if a type has multiple constructors, one of which does not assign a value to @color?
class Baz
def initialize(color)
@color = color
end
def color
@color
end
def color=(value)
@color = value
end
end
Instance variables in ruby are not “defined” per se. They pop into existence when they are used.
The first time you assign something to an instance variable, that is the closest thing to a “definition” (but really it is more of an “initialization”). If you reference an instance variable that has not been assigned a value yet, its value will be
nil.So if your constructor does not assign a value to
@color, then@colorwill simply remain uninitialized (and thus returnnilanywhere else in the class that references it…unless it is assigned a value elsewhere outside the constructor).See here for more information: http://www.rubyist.net/~slagell/ruby/instancevars.html
A relevant quote from the article:
And: