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

如何在2个其他已包含的模块之间混合ruby模块?

发布时间:2020-12-17 02:38:31 所属栏目:百科 来源:网络整理
导读:假设存在以下代码: module Foo def test(x) "Foo #{x}" endendmodule Bar def test(x) "Bar #{x} " + super endendclass C include Foo include Barendputs C.new.test(2)# = "Bar 2 Foo 2" 我无法访问C类代码,也无法访问模块Foo和Bar. 我想在Foo和Bar之间
假设存在以下代码:

module Foo
  def test(x)
    "Foo #{x}"
  end
end

module Bar
  def test(x)
    "Bar #{x} " + super
  end
end

class C
  include Foo
  include Bar
end

puts C.new.test(2)
# => "Bar 2 Foo 2"

我无法访问C类代码,也无法访问模块Foo和Bar.

我想在Foo和Bar之间包含一个模块,这样:

module Between
  def test(x)
    "Between " + super
  end
end

puts C.new.test(2)
# => "Bar 2 Between Foo 2"

这是如何实现的?

解决方法

module Bar; include Between end
class C; include Bar end
puts C.new.test(2)
#=> Bar 2 Between Foo 2

但请注意,在实践中,应避免使用这种无意义的模块杂耍.

(编辑:李大同)

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

    推荐文章
      热点阅读