class Animal
def initialize(noise)
@noise = noise
end
def say
puts "#{self.class} does #{@noise}"
end
end
dog = Animal.new("Woof Woof")
cat = Animal.new("Meow Meow")
dog.say
cat.say
如何打印 dog does woof woof
而不是 Animal does Woof Woof
?
最佳答案
需要说明的是,Animal 是您创建的类的名称。这就是为什么当你
puts " #{self.class} etc... "
Animal 文本出现。
现在在您的示例中,cat 和 dog 是变量的名称。这些只不过是对您在行中创建的对象的引用:
dog = Animal.new("Woof Woof")
cat = Animal.new("Meow Meow")
变量可能被称为狗或猫,但类仍然是动物。据我所知,除了一些非常复杂的自省(introspection)工具外,没有什么好的方法可以获取变量的名称。
另一方面:如果您只是想让您的动物有名字,请考虑添加名称属性。
class Animal
def initialize(name, noise)
@name = name
@noise = noise
end
def say
puts "#{@name} does #{@noise}"
end
end
dog = Animal.new("Dog", "Woof Woof")
cat = Animal.new("Cat", "Meow Meow")
dog.say
cat.say
关于ruby - 在ruby中获取对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120794/