gpt4 book ai didi

ruby - 如何在 ruby​​ 中解析符号

转载 作者:数据小太阳 更新时间:2023-10-29 07:52:10 26 4
gpt4 key购买 nike

一本书上说,我们在ruby中声明/初始化/定义的所有标识符和变量都会作为符号包含在内部符号表中;然后,每当程序中的任何地方使用包含的符号时,Ruby 都会查找它。例如,在程序中:

  • a = "1"
  • Ruby 在其表中包含变量 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com