加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 为什么在include之后可以将实例方法作为模块方法调用?

发布时间:2020-12-17 02:45:52 所属栏目:百科 来源:网络整理
导读:在模块上定义的实例方法: module A def foo; :bar endend 当包含该模块时,似乎可以将其作为该模块的模块方法调用: include AA.foo # = :bar 这是为什么? 解决方法 你将A包含在对象中. module A def self.included(base) puts base.inspect #Object end de
在模块上定义的实例方法:

module A
  def foo; :bar end
end

当包含该模块时,似乎可以将其作为该模块的模块方法调用:

include A
A.foo # => :bar

这是为什么?

解决方法

你将A包含在对象中.

module A
  def self.included(base)
    puts base.inspect #Object
  end

  def foo
    :bar
  end
end

include A

puts A.foo # :bar
puts 2.foo # :bar

#puts BasicObject.new.foo   #this will fail

还要注意顶级对象main是特殊的;它既是Object的实例,也是Object的一种委托者.

见http://banisterfiend.wordpress.com/2010/11/23/what-is-the-ruby-top-level/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读