【问题标题】:Class variables and inheritance. Subclass specific variables?类变量和继承。子类特定变量?
【发布时间】:2018-04-16 00:39:58
【问题描述】:

我在子类化和类变量方面有点挣扎。我期待子类的类方法调用设置的类变量特定于该子类,但我看到它们是在超类中设置的。

例如,如果我运行以下代码:

class Obj
    @@can_say = []
    def self.says word
        @@can_say.push(word)
    end

    def self.listens_to calling
        define_method calling do
            "I say #{@@can_say}"
        end
    end
end

class Dog < Obj
    says "woof"
    says "bark bark"
    listens_to "goodboy"
end

class Cat < Obj
    says "meaow"
    says "purr"
    listens_to "lord"
end

cat = Cat.new
dog = Dog.new

puts("Dog: #{dog.goodboy}")
puts("Cat: #{cat.lord}")

我明白了:

ruby/test$ ruby test.rb 
Dog: I say ["woof", "bark bark", "meaow", "purr"]
Cat: I say ["woof", "bark bark", "meaow", "purr"]

我期待:

ruby/test$ ruby test.rb 
Dog: I say ["woof", "bark bark"]
Cat: I say ["meaow", "purr"]

有没有办法做到这一点?

【问题讨论】:

标签: ruby


【解决方案1】:

我找到了一种方法:

class Obj
    class << self
        attr_accessor :can_say
    end

    def self.says word
        if @can_say.nil?
            @can_say = Array.new
        end
        @can_say.push(word)
    end

    def self.listens_to calling
        define_method calling do
            "I say #{self.class.can_say}"
        end
    end
end

class Dog < Obj
    says "woof"
    says "bark bark"
    listens_to "goodboy"
end

class Cat < Obj
    says "meaow"
    says "purr"
    listens_to "lord"
end

cat = Cat.new
dog = Dog.new

puts("Dog: #{dog.goodboy}")
puts("Cat: #{cat.lord}")

如果我能以某种方式摆脱:

if @can_say.nil?
    @can_say = Array.new
end

【讨论】:

  • 你可以使用这个(@can_say ||= []) &lt;&lt; word 来摆脱它,它只是在说同样的事情,但在一行中,如果没有找到它只会创建一个数组或附加到现有的数组如果找到
  • 谢谢@Subash,知道这很有帮助!有没有其他方法可以事先声明和初始化@cas_say
  • (@can_say ||= []) 这一行在这里没有附加word 正在做空数组的初始化
猜你喜欢
  • 2013-08-16
  • 2013-02-11
  • 1970-01-01
  • 2015-12-09
  • 2019-03-28
  • 2014-01-18
  • 2013-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多