作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
一本书上说,我们在ruby中声明/初始化/定义的所有标识符和变量都会作为符号包含在内部符号表中;然后,每当程序中的任何地方使用包含的符号时,Ruby 都会查找它。例如,在程序中:
a = "1"
a
作为 :a
。a
在程序中使用:
def a
puts "stack_overflow"
end
变量a
和标识符def a
中存储了单个符号:a
。我使用 Symbol.all_symbols.count
检查了符号数。计数是一样的;即,添加 def a
不会增加符号表计数。
当 ruby 在代码中的任何地方看到 a
时,它如何区分变量 a
和标识符 def a
?
在s = :x
中,符号变量s
是存储在符号表中,还是只是:x
?
最佳答案
The count was the same; i.e., adding
def a
did not increase the symbol table count.
这是因为符号:a
已经存在了:
$ ruby -e "puts Symbol.all_symbols.count"
2504
$ ruby -e "puts Symbol.all_symbols" | grep ^a | sort | head -n 5
a
abort
abort_on_exception
abort_on_exception=
abs
您可以使用 --disable-gems
选项启动 Ruby 以摆脱它(以及许多其他符号):
$ ruby --disable-gems -e "puts Symbol.all_symbols.count"
1689
$ ruby --disable-gems -e "puts Symbol.all_symbols" | grep ^a | sort | head -n 5
abort
abort_on_exception
abort_on_exception=
abs
abs2
现在,定义或引用 a
实际上会增加符号计数:
$ ruby --disable-gems -e "puts Symbol.all_symbols.count"
1689
$ ruby --disable-gems -e "def a; end; puts Symbol.all_symbols.count"
1690
$ ruby --disable-gems -e "a = 1; puts Symbol.all_symbols.count"
1690
关于ruby - 如何在 ruby 中解析符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34176710/
我是一名优秀的程序员,十分优秀!