class Collie
    def speak
        puts dog_generic
    end
end

class Greyhound
    def speak
        puts dog_generic
    end
end

class Labrador
    def speak
        puts dog_generic
    end
end

dog_generic = "Woof"

chep = Collie.new
wrex = Collie.new
speedy = Greyhound.new
faithful = Labrador.new

chep.speak #=> Woof
wrex.speak #=> Woof
speedy.speak #=> Woof
faithful.speak #=> Woof

我想最后三种方法都返回“Woof”但是,此代码将调用未定义的变量dog_generic error这似乎是因为即使是全局变量也不能用于对象如果我将dog_generic的所有实例都更改为@@dog_generic,它将起作用,但@@ variables很少使用,仅基于此,我不禁认为我做错了。
如何在多个对象之间共享一个变量?
不,我不想把一串“Woof”作为参数传递给每个对象。

最佳答案

通常,人们会使用继承来提供这种行为:

class Dog
    def speak
        puts "Woof"
    end
end

class Collie < Dog
   # whatever behavior that is specific to Collie here
end

chep = Collie.new
chep.speak #=> Woof

关于ruby - 在多个对象中共享一个变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19484694/

10-13 04:49