下面的代码什么也没打印,我期待welcomeBack
. 请解释。
class Hello
@instanceHello = "welcomeBack"
def printHello
print(@instanceHello)
end
Hello.new().printHello();
end
我刚开始学习红宝石,所以如果问题看起来很愚蠢,请原谅。
下面的代码什么也没打印,我期待welcomeBack
. 请解释。
class Hello
@instanceHello = "welcomeBack"
def printHello
print(@instanceHello)
end
Hello.new().printHello();
end
我刚开始学习红宝石,所以如果问题看起来很愚蠢,请原谅。
如果你只能记住关于定义方法和设置变量的一件事,那就是:总是问自己,此时此刻是什么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();