关于Ruby Koans中的_scope.rb的问题
我现在正在做Ruby Koans练习,在理解以下代码中作用域的工作原理时遇到了一些困难:关于Ruby Koans中的_scope.rb的问题,ruby,scope,Ruby,Scope,我现在正在做Ruby Koans练习,在理解以下代码中作用域的工作原理时遇到了一些困难: class AboutScope < Neo::Koan module Jims class Dog def identify :jims_dog end end end class String end def test_nested_string_is_not_the_same_as_the_system_string
class AboutScope < Neo::Koan
module Jims
class Dog
def identify
:jims_dog
end
end
end
class String
end
def test_nested_string_is_not_the_same_as_the_system_string
assert_equal false, ::String == "HI".class
end
def test_you_can_get_a_list_of_constants_for_any_class_or_module
assert_equal [:Dog], Jims.constants
end
end
class AboutScope
关于上述代码,我有两个问题:
::String
的类是String[:Dog]
而不是[“Dog”]
AboutScope
的命名空间中。默认情况下,String
将引用AboutScope::String
。为了引用根环境中的字符串
(或对象
中的字符串),附加了:
。有了它,::String
指的是根字符串
Module#constants
通过设计,返回以符号表示的常量名称数组。它可能被设计为返回字符串数组,但对于表示封闭类静态内容,符号比字符串更适合。特别是在最近的Ruby之前,每次读取新字符串文本时都会新建字符串,而对于同一符号的不同出现,只会创建一次符号。对于可能在代码中多次调用的东西,将它们作为符号而不是字符串更有效为什么会是
[“Dog”]
?您的代码没有正确关闭。谢谢!我合上了:)+1。除#2之外,符号:Dog
已经存在,因为常量名称会自动插入(请参阅symbol.all_符号
),因此返回已经存在的符号比初始化新字符串“Dog”
要简单得多。谢谢您的回答。现在我更清楚了。