以下代码什么都没打印,我期待welcomeBack
。请解释一下。
class Hello
@instanceHello = "welcomeBack"
def printHello
print(@instanceHello)
end
Hello.new().printHello();
end
我刚刚开始倾向于红宝石,所以如果问题看起来很愚蠢,请原谅。
答案 0 :(得分: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
如果要为ivar设置默认值,请在构造函数中执行:
class Hello
def initialize
@instanceHello = "welcomeBack"
end
def printHello
print @instanceHello
end
end
Hello.new.printHello # >> welcomeBack
答案 1 :(得分:3)
在Ruby中,实例变量是在实例方法中定义和使用的。因此,您需要将作业放在initialize
方法中:
class Hello
def initialize
@instanceHello = "welcomeBack"
end
def printHello
print(@instanceHello)
end
end
Hello.new.printHello();
另外,请注意我将printHello调用移到了类定义之外。这是因为该类在第一次关闭之前才实际定义;也就是说,在最后end
之后。
答案 2 :(得分:0)
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"]
答案 3 :(得分:0)
将@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();