Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instance variable declaration

Tags:

ruby

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.

like image 522
Sajan Chandran Avatar asked Feb 22 '26 10:02

Sajan Chandran


2 Answers

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
like image 83
Sergio Tulentsev Avatar answered Feb 27 '26 08:02

Sergio Tulentsev


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.

like image 22
marcus erronius Avatar answered Feb 27 '26 10:02

marcus erronius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!