Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.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
RubyMonk 8.2模块作为名称空间_Ruby - Fatal编程技术网

RubyMonk 8.2模块作为名称空间

RubyMonk 8.2模块作为名称空间,ruby,Ruby,总的来说,我很难理解Ruby中的一些概念,模块就是其中之一 我正处于RubyMonk 8.2的最后一步:模块作为名称空间,我非常迷茫。我该怎么办?我的计划是获取解决方案并对其进行反向工程,但没有解决方案按钮,因此我被卡住了:( 说明如下: 如果在常量前面加上::而不加父级,则作用域发生在最顶层。在本练习中,在Kata模块之外的最顶层中,将push更改为按a=10返回10 module Kata A = 5 module Dojo A = 7 class ScopeIn

总的来说,我很难理解Ruby中的一些概念,模块就是其中之一

我正处于RubyMonk 8.2的最后一步:模块作为名称空间,我非常迷茫。我该怎么办?我的计划是获取解决方案并对其进行反向工程,但没有解决方案按钮,因此我被卡住了:(

说明如下:

如果在常量前面加上::而不加父级,则作用域发生在最顶层。在本练习中,在Kata模块之外的最顶层中,将push更改为按a=10返回10

module Kata
  A = 5
  module Dojo
    A = 7
    class ScopeIn
      def push0
        A
      end
      def push1
        Kata::Dojo::A
      end
      def push2
        Kata::A 
      end
      def push3
        ::A
      end
    end
  end
end
A = 10

scope = Kata::Dojo::ScopeIn.new #=> #<Kata::Dojo::ScopeIn:0x007fe63c8381d0> 

scope.push0 #=>  7 
scope.push1 #=>  7
scope.push2 #=>  5 
scope.push3 #=> 10
已填写的代码为:

module Kata
  A = 5

  module Dojo
    B = 9
    A = 7

    class ScopeIn
      def push
       A
      end
    end
  end
end
A = 10
那么,你想要这个:

module Kata
  A = 5  
  module Dojo
    B = 9
    A = 7

    class ScopeIn
      def push
       ::A # change this line from A to ::A, meaning ::A will refer to the top-level namespaced A which is defined outside the Kata module (A = 10)
      end
    end
  end
end

A = 10
p Kata::Dojo::ScopeIn.new.push
# => 10
如果在常量前面加上
::
而没有父级,则作用域发生在最顶层。在本例中,
push
将返回
10
,因为
a=10
位于Kata模块之外的最顶层。

模块Kata
module Kata
  A = 5
  module Dojo
    A = 7
    class ScopeIn
      def push0
        A
      end
      def push1
        Kata::Dojo::A
      end
      def push2
        Kata::A 
      end
      def push3
        ::A
      end
    end
  end
end
A = 10

scope = Kata::Dojo::ScopeIn.new #=> #<Kata::Dojo::ScopeIn:0x007fe63c8381d0> 

scope.push0 #=>  7 
scope.push1 #=>  7
scope.push2 #=>  5 
scope.push3 #=> 10
A=5 模块Dojo A=7 类作用域 def push0 A. 结束 def推送1 Kata::Dojo::A 结束 def推送2 卡塔:A 结束 def推送3 ::A 结束 结束 结束 结束 A=10 scope=Kata::Dojo::ScopeIn.new#=># scope.push0#=>7 scope.push1#=>7 scope.push2#=>5 scope.push3#=>10
DJBrandoK,让我知道这是否解决了你的问题,还有如果你有任何后续问题。谢谢。如果它解决了你的问题,然后考虑接受答案(勾勾勾勾)。。若要了解更多关于接受答案的工作原理,请参阅此帖子:听起来不错。我接受了答案。这是我关于Stackoverflow的第一篇帖子,因此我仍在学习。感谢您的帮助!非常欢迎您使用Stackoverflow:)我成功地使用了第二个回复,但也感谢您的帮助!