在Ruby中,为什么我的基类只放一次?

时间:2013-06-03 15:12:33

标签: ruby class inheritance

我很高兴知道为什么下面"Cat"的实例也没有将"This animal can:"文本放在其特定实例属性之前。我期待这样的输出:

This animal can:
Say it's name: 'Rover'
Bark
This animal can:
Say its name: 'Satan'
Meow

以下是代码:

class Animal
    puts "This animal can:"
end

class Dog < Animal
    def initialize(name)
        @name = name
        puts "Say its @name: '%s'" % [name]
    end
    def bark
        puts "Bark"
    end
end

class Cat < Animal
    def initialize(name)
        @name = name
        puts "Say its @name: '%s'" % [name]
    end
    def meow
        puts "Meow"
    end
end

rover = Dog.new("Rover").bark
satan = Cat.new("Satan").meow

我所看到的是:

This animal can:
Say it's name: 'Rover'
Bark
Say its name: 'Satan'
Meow

"cat"类还没有继承Animal类吗?它的输出不应该以{{1​​}}开头吗?

5 个答案:

答案 0 :(得分:5)

代码中的问题是:

puts "This animal can:"
定义Animal类时运行

。看起来你想在初始化器中使用它:

class Animal
  def initialize(name)
    puts "This animal can:"
  end
end

然后,您需要在其他初始值设定项中调用super以获得您期望的结果。

答案 1 :(得分:2)

“This Animal can:”行仅在定义类时发生,因为它不存在于方法中。由于两个动物在初始化器中都有共同的行为,因此您可能希望将初始化器提升为Animal类。

class Animal
  def introduce_myself
    puts "Hello! My name is #{@name} and I know how to: "
  end

  def initialize(name)
    @name = name
    introduce_myself
  end
end

class Dog < Animal
  def bark
    puts "Woof!"
  end
end

class Cat < Animal
  def meow
    puts "Meow!"
  end
end

Dog.new("Fido").bark
Cat.new("Sparky").meow

输出:

Hello! My name is Fido and I know how to: 
Woof!
Hello! My name is Sparky and I know how to: 
Meow!

答案 2 :(得分:1)

您的Animal类没有定义构造函数,也没有被继承者调用:

class Animal
   def initialize
      puts "This animal can:"
   end
end

class Dog < Animal    
   def initialize(name)
       super()
       @name = name
       puts "Say its @name: '%s'" % [name]
   end

   def bark
       puts "Bark"
   end    
end

答案 3 :(得分:0)

完全!

class Animal
  def initialize(name)
    puts "This animal can:"
  end
end

def initialize(name)
  @name = name
  puts "Say its @name: '%s'" % [name]
  super # initializer from parent class
end

为什么不起作用?

class Animal
  puts "This animal can:"
end

当ruby解析器读取代码时,它会在途中评估所有内容。我的意思是即使你不会创造任何物体,它也会显示出来#34;这种动物可以:&#34;这就是为什么你第一次看到这个并且让人觉得Dog class工作正常的原因

答案 4 :(得分:-1)

安装name_magicgem install y_support)并享受乐趣

require 'y_support/name_magic';     

class Animal
  include NameMagic
  def initialize; puts "This animal #{sound}s." end
  def sound; "growl" end
  def speak; puts "#{sound.capitalize}!" end
end

class Dog < Animal
  def sound; "bark" end
end

class Cat < Animal
  def sound; "meow" end
end

def hullo( animal )
  Animal.instance( animal ).speak
end

Rover = Dog.new
#=> This animal barks.
Satan = Cat.new
#=> This animal meows.

hullo :Rover
#=> Bark!

Animal.instances.each( &:speak )
#=> Bark!
#=> Meow!