1

Koan 代码,编号 75:

      in_ruby_version("mri") do
        RubyConstant = "What is the sound of one hand clapping?"
        def test_constants_become_symbols
          all_symbols = Symbol.all_symbols

          assert_equal __, all_symbols.include?(__)
        end
      end

我对此有点困惑,因为我刚刚发现针对“all_symbols.include?(__)”测试的任何符号都将匹配“true”。例如,以下所有内容都应该有效:

    assert_equal true, all_symbols.include?(:RubyConstant)
    assert_equal true, all_symbols.include?(:"What is the sound of one hand clapping?")
    assert_equal true, all_symbols.include?(:AnythingElseYouCouldWriteHere)

用“constants_become_symbols”学到什么?

4

1 回答 1

5

在 ruby​​ 中,以大写字母开头的变量成为常量。koan 的目标是教你常量成为 ruby​​ 中的符号并被添加到 ruby​​ 的符号表中。

in_ruby_version("mri") do
  RubyConstant = "What is the sound of one hand clapping?"
  def test_constants_become_symbols
    all_symbols = Symbol.all_symbols

    assert_equal true, all_symbols.include?("RubyConstant".to_sym)
  end
end

还要注意它是怎么说"RubyConstant".to_sym的,而不是:RubyConstant. 这是为了避免混淆,因为 ruby​​ 解释器在解析 ruby​​ 函数时会自动创建一个符号,如此所述。

于 2012-11-28T08:02:59.123 回答