If you could memorize only one thing about defining methods and setting variables, it's this: always ask yourself, what is self at this point?
class Hello
# This ivar belongs to Hello class object, not instance of Hello.
# `self` is Hello class object.
@instanceHello = "welcomeBack"
def printHello
# Hello#@instanceHello hasn't been assigned a value. It's nil at this point.
# `self` is an instance of Hello class
print @instanceHello
end
def self.printSelfHello
# Now this is Hello.@instanceHello. This is the var that you assigned value to.
# `self` is Hello class object
print @instanceHello
end
end
Hello.new.printHello # >>
Hello.printSelfHello # >> welcomeBack
If you want to set a default value for an ivar, do it in the constructor:
class Hello
def initialize
@instanceHello = "welcomeBack"
end
def printHello
print @instanceHello
end
end
Hello.new.printHello # >> welcomeBack