好的,我有一个关于如何在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
现在前面所说的def已经过了新的一个,所以现在如果事情传递说它会返回它而不是通过它。有没有办法在红宝石中这样做?感谢
答案 0 :(得分:2)
以下是三个文件的示例:animal.rb
,dog.rb
和script.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
答案 1 :(得分: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