The following code prints nothing, I was expecting welcomeBack. Please explain.
class Hello
@instanceHello = "welcomeBack"
def printHello
print(@instanceHello)
end
Hello.new().printHello();
end
I just started to lean ruby, so please forgive if the question looks dumb.
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
In Ruby, instance variables are defined and used in instance methods. So you need to put your assignment in the initialize method:
class Hello
def initialize
@instanceHello = "welcomeBack"
end
def printHello
print(@instanceHello)
end
end
Hello.new.printHello();
Also, note that I moved the printHello call outside of the class definition. This is because the class isn't actually defined until after it is closed the first time; that is, after the last end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With