0

我很高兴知道为什么"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类吗?它的输出不应该也以 开头"This animal can:"吗?

4

5 回答 5

5

您的代码中的问题是:

puts "This animal can:"

在定义 Animal 类时运行。似乎您希望在初始化程序中使用它:

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

然后,您需要调用super其他初始化程序以获得您期望的结果。

于 2013-06-03T15:16:14.070 回答
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!
于 2013-06-03T15:20:06.773 回答
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
于 2013-06-03T15:17:57.137 回答
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​​ 解析器读取代码时,它会评估所有内容。我的意思是,即使你不创建任何对象,它也会显示“这个动物可以:”这就是为什么你第一次看到它并且觉得 Dog 类可以正常工作的原因

于 2013-06-03T15:20:38.863 回答
-1

安装name_magic( gem 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!
于 2013-06-03T16:08:23.560 回答