【问题标题】:In Ruby what does the line "class ClassName < Base" mean in this context在 Ruby 中,“class ClassName < Base”这一行在这种情况下是什么意思
【发布时间】:2011-10-22 22:48:20
【问题描述】:

给定代码

require 'gdata'

class Contacts
  class Gmail < Base

当我们说“

还是有别的意思?

【问题讨论】:

  • 您是否想知道具体的冲突?
  • 不,我并不担心特定的冲突,我想知道 Base 是否意味着特殊的东西,或者它是否应该来自“gdata”。我还遇到了另一个 sn-p,其中有许多必需的语句。因为我没有看到它像通常那样被命名空间(比如在 Activerecord::Base 中),所以我想知道它是否有特殊含义。

标签: ruby class inheritance module base


【解决方案1】:

Base 没有特殊含义。

ruby-1.9.2-p180 :001 > Base.inspect
NameError: uninitialized constant Object::Base

除非在 gdata 中定义了名为 Base 或 Contacts::Base 的类,否则该示例应生成错误。

class Base
  def self.hello
    "oh hi!"
  end
end

class Base2
  def self.hello
    "ahoy!"
  end
end

class Contacts
  class Base
    def self.hello
      "hi 2 u"
    end
  end
  class Gmail < Base
  end
  class Gmail2 < Base2
  end
end

ruby-1.9.2-p180 :024 > Base.hello
 => "oh hi!" 
ruby-1.9.2-p180 :025 > Contacts::Gmail.hello
 => "hi 2 u" 
ruby-1.9.2-p180 :026 > Contacts::Gmail2.hello
 => "ahoy!" 

【讨论】:

  • 谢谢Kimmmo,所以“
【解决方案2】:

Gmail 类只是一个普通的嵌套类定义,恰好是Base 的子类。显然Base 是在文件gdata 的某处定义的,但它没有说gdata 是一个Ruby 模块,如果它是一个模块,你没有显示它被混入( include) Contacts 所以我不确定是否有任何冲突需要担心。

【讨论】:

  • 谢谢 Ray “显然 Base 是在文件 gdata 的某处定义的”——这回答了我的问题。由于我在 ActiveRecord::Base 中遇到过“Base”,因此我想知道它是否是公开某些功能的通用名称。由于在这个例子中它没有命名空间,我想知道它是来自“gdata”还是来自更高层次的某个地方。
猜你喜欢
  • 2020-04-04
  • 2017-03-28
  • 2016-08-26
  • 1970-01-01
  • 2014-10-27
  • 2019-10-15
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多