实例变量声明

以下代码什么都没打印,我期待welcomeBack 。 请解释。

 class Hello @instanceHello = "welcomeBack" def printHello print(@instanceHello) end Hello.new().printHello(); end 

我刚刚开始倾向于ruby,所以如果问题看起来很愚蠢,请原谅。

如果你只能记住定义方法和设置变量的一件事,那就是:总是问问自己,此时的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 

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

 class Hello def initialize @instanceHello = "welcomeBack" end def printHello print @instanceHello end end Hello.new.printHello # >> welcomeBack 

在Ruby中,实例变量在实例方法中定义和使用。 所以你需要把你的作业放在initialize方法中:

 class Hello def initialize @instanceHello = "welcomeBack" end def printHello print(@instanceHello) end end Hello.new.printHello(); 

另外,请注意我将printHello调用移到了类定义之外。 这是因为该类在第一次关闭之后才实际定义; 也就是说,在最后一个end

 class Hello @instanceHello = "welcomeBack" def printHello puts self.class.instance_variable_get(:@instanceHello) end Hello.new.printHello; #=> welcomeBack end 

这不是很好的编程,只是为了说明一个类(它是类Class的一个实例)也可以像任何其他实例一样拥有实例变量。 它们被称为“类实例变量”,并且比类变量更受欢迎。 以下示例说明了如何在类级别定义计数器:

 class Hello @counter = 0 class << self # access methods for class instance variables must be # defined in the singleton class attr_accessor :counter end def printHello self.class.counter += 1 puts "Hello #{self.class.counter}" end end Hello.new.printHello; #=> Hello 1 Hello.new.printHello; #=> Hello 2 p Hello.singleton_methods #=> ["counter=", "counter"] 

将@instanceHello更改为self.class.instance_variable_get(:@ instanceHello)

@instanceHello是一个类实例变体

代码是这样的:

  class Hello @instanceHello = "welcomeBack" @@classHello = "greeting!" def printHello print(self.class.instance_variable_get(:@instanceHello)) print(self.class.class_variable_get(:@@classHello)) end end Hello.new().printHello();