实例变量声明

Saj*_*ran 3 ruby

以下代码没有打印,我期待welcomeBack.请解释.

class Hello

  @instanceHello = "welcomeBack"

  def printHello
    print(@instanceHello)
  end

  Hello.new().printHello();
end
Run Code Online (Sandbox Code Playgroud)

我刚刚开始倾向于红宝石,所以如果问题看起来很愚蠢,请原谅.

Ser*_*sev 7

如果你只能记住定义方法和设置变量的一件事,那就是:总是问问自己,到底是什么self

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
Run Code Online (Sandbox Code Playgroud)

如果要为ivar设置默认值,请在构造函数中执行以下操作:

class Hello

  def initialize
    @instanceHello = "welcomeBack"
  end

  def printHello
    print @instanceHello
  end
end

Hello.new.printHello # >> welcomeBack
Run Code Online (Sandbox Code Playgroud)