Reputation: 1127
If I make @x
lazily loaded in the parent class A
it can be called and initialized just fine, but if I try to call it from A
's subclass B
, then it won't call @x
's initialization method and returns nil
. Why is that?
class A
def x
@x ||= 'x'
end
end
puts A.new.x # 'x'
class B < A
def use_x
puts @x.inspect # nil
end
end
Upvotes: 1
Views: 125
Reputation: 168101
Because the method x
is not called within use_x
. Whether it is A
or B
is irrelevant. puts B.new.x
would give the same result as it would with puts A.new.x
.
Upvotes: 0
Reputation: 369094
Use x
instead of directly accessing the instance variable @a
.
class B < A
def use_x
puts x.inspect
end
end
Upvotes: 2