Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何添加到包含的模块_Ruby - Fatal编程技术网

Ruby 如何添加到包含的模块

Ruby 如何添加到包含的模块,ruby,Ruby,考虑下面的代码,这将理想地使我能够引用Shelf::ThingOne和Shelf::ThingTwo: module Things class ThingOne end end class Shelf include Things module Things class ThingTwo end end end Shelf::Things.constants # => [:ThingTwo] 模块内容的第二个声明已覆盖第一个声明。是否可以重新打开包

考虑下面的代码,这将理想地使我能够引用
Shelf::ThingOne
Shelf::ThingTwo

module Things
  class ThingOne
  end
end

class Shelf
  include Things
  module Things
    class ThingTwo
    end
  end
end

Shelf::Things.constants # => [:ThingTwo]
模块内容的第二个声明已覆盖第一个声明。是否可以重新打开包含的模块,以便在其中嵌套更多(例如)类


编辑:事实证明这不是我想要回答的问题。我已经问了一个后续问题,

看起来您是有意重写模块
内容
,将
ThingTwo
类嵌套在
工具架
中,要求ruby在
工具架
类中查找常量。您不必两次声明同一模块,请尝试:

module Things
  class ThingOne
  end
end

class Shelf
  include Things
  class ThingTwo
  end
end
你会得到

=> [:Things, :ThingTwo, :ThingOne] 

当您将模块包含到类中时,将包含它们的方法,而不是类。因此,在完成您所做的工作之后,您可以在
Shelf
实例中使用
ThingOne
中的方法

如果要使用
Shelf::ThingOne
Shelf::ThingTwo
,则需要在模块中嵌套这两个声明(Ruby中的模块和类可以在多个文件中定义):

另见

module
Things
的第二个声明已经覆盖了第一个声明

不,没有
Shelf::Things
是一个与
::Things
完全无关的模块

Things.constants # => [:ThingOne]
Shelf::Things.constants # => [:ThingTwo]
这将理想地导致我能够引用
Shelf::ThingOne
Shelf::ThingTwo::ThingTwo


但是,正如其他答案中已经暗示的那样,这是非常不规则的,这种“继承”常量。很可能您为该工作选择了一个错误的工具,但很难判断,因为。

这没有帮助-所有
extend
所做的就是将
ThingOne
直接放入
Shelf
的命名空间中。我不想这样——我已经编辑了这个问题,让它更清楚。1)是的,这一点很清楚;2) 这不是Ruby在其他情况下的工作方式-
classfoo;def hi;打招呼;结束;结束;Foo类;再见;“再见”;结束
工作正常;3) “我想知道我如何才能最终不覆盖它。@Chowlett抱歉,我是stackoverflow的新手,我的答案刚刚编辑好,不担心自己是新手。问题是,如果在Ruby中重新打开一个类定义,通常最终会添加到类中(如我的第二条评论)。这里显然不是这样;我想知道如何让它工作。“当你将一个模块包含到一个类中时,它们是方法而不是包含的类”——严格来说,这不是真的。这就好像模块被“粘贴”到类中一样。因此,如果
ThingOne
定义了一个函数
foo
,那么
Shelf
实例就不能调用
foo
。但是
Shelf::ThingOne
将是一个类,
Shelf::ThingOne
实例可以调用
foo
…哦!我没有发现这一点,即使我没有直接在
Shelf
中打开
Things
,我也没有从include中获得
Shelf::ThingOne
。呵呵。那么,有没有办法让我得到我想要的?
Shelf::ThingOne
Shelf::ThingOne::ThingTwo
,其中
ThingOne
包括一个模块?@Chowlett查看更新,尽管您可能不喜欢答案:)嗯,我明白了。我可能过于简化了(我的实际情况隐藏在一个复杂的Rails应用程序中)。我会看看我是否能给出一个最简单的例子,更接近我实际面临的问题。@Chowlett:是的,a将是完美的。不过,把它当作另一个问题来问。不要完全改变这一点。是的,我在发帖时以为我有一个,但我离“完成”还有一两步。当我有它的时候,我会链接。
Things.constants # => [:ThingOne]
Shelf::Things.constants # => [:ThingTwo]
module Things
  class ThingOne
  end
end

class Shelf
  module Things
    ThingOne = ::Things::ThingOne

    class ThingTwo
    end
  end
end

Shelf::Things.constants # => [:ThingOne, :ThingTwo]