【发布时间】:2019-07-02 22:26:55
【问题描述】:
以下有Universe(超类)、Common(模块)、FlatEarthBelievers(子类)和RoundEarthBelievers(子类)。输出有错误,想要让它工作,任何指针?
这是关于继承和混合的,子类从一个公共父类继承并希望利用与父类行为无关的公共方法。我希望能够从包含/扩展它的 Child 类中的公共模块调用方法。我对它的用法感到困惑,因为我想将这些常用方法同时视为类方法和实例方法。
class Universe
$knowledge = "Universe comprises of galaxies, stars, planets, steroids, meteoroids, comets, etc"
def universe_comprises_of
puts $knowledge
end
end
module Common
$earth_is = Hash.new
def init(earth_is)
$earth_is = earth_is
end
def statement
puts " Earth is " + $earth_is["attribute"].to_str
end
end
class FlatEarthBelievers < Universe
include Common
earth_is = { :attribute => "Flat !" }
init(earth_is)
end
class RoundEarthBelievers < Universe
include Common
earth_is = { :attribute => "Round like an Orange!" }
Common.init(earth_is)
end
moron = FlatEarthBelievers.new
moron.universe_comprises_of
moron.statement
sensible_person = RoundEarthBelievers.new
sensible_person.universe_comprises_of
sensible_person.statement
【问题讨论】:
-
请用每个类的代码块格式化您的帖子,详细说明错误并解释您想要做什么,代码中有一些格式错误,但我认为这是因为您的 C/P
-
FWIW,变量名以
$开头是'un-Ruby-like' -
为什么? THIS_IS_A_CONSTANT、@instance_variable、local_variable、$global_variable 更多在这里
-
“有一个错误”不是一个足够精确的错误描述,我们无法帮助您。 什么不起作用? 如何不起作用?你的代码有什么问题?您收到错误消息吗?错误信息是什么?你得到的结果不是你期望的结果吗?你期望什么结果,为什么,你得到的结果是什么,两者有什么不同?您正在观察的行为不是期望的行为吗?期望的行为是什么,为什么,观察到的行为是什么,它们有何不同?
-
@NMPennypacker:这不仅仅是“不像 Ruby”。使用全局变量通常不像编程。永远。
标签: ruby-on-rails ruby subclass mixins superclass