-1

好的,我有一个关于如何在 ruby​​ 中做某事的问题。我有一个 python 示例来展示我的目标,所以就到这里了。

 class TestScript:
       def say(word):
           pass
       def x():
           self.say("hello") #right now it will pass

假设该模块被称为“tester.py”,但现在,在另一个模块中,我们现在可以这样做:

 import tester
 class doScript(tester.TestScript):
       def say(word):
           return word #now its overrided so in this current module it will return it rather pass it

现在,之前通过的 say def 被新的声明无效,所以现在如果有东西被传递,它会返回它而不是通过它。有没有办法在红宝石中做到这一点?谢谢

4

2 回答 2

2

这是一个包含三个文件的示例:animal.rbdog.rbscript.rb.

# animal.rb
# Our base class.
class Animal
  def speak
    puts 'click-click'
  end
  def eat
    puts 'chomp-chomp'
  end
end

# dog.rb
# Dog inherits from Animal, but we override the speak() method.
require 'animal'

class Dog < Animal
  def speak
    puts 'woof-woof'
  end
end

# script.rb
# Demo script.
require 'dog'

d = Dog.new
d.speak
d.eat
于 2013-09-22T16:49:27.900 回答
0

您始终可以从其他类继承:

class BasicSay
  def say(text)
    puts prepare_text(text)
  end

  def prepare_text(text)
    do_something_with(text)
  end
end

class HtmlSay < BasicSay
  def say(text)
    "<p>" + prepare_text(text) + "</p>"
  end
end
于 2013-09-22T05:05:52.523 回答