从RubyKoanº75学习什么?

Alv*_*nço 1 ruby

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
Run Code Online (Sandbox Code Playgroud)

我对它有点困惑,因为我刚刚发现任何针对"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)
Run Code Online (Sandbox Code Playgroud)

用"constants_become_symbols"来学习什么?

小智 5

在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
Run Code Online (Sandbox Code Playgroud)

还要注意它是如何"RubyConstant".to_sym代替的:RubyConstant.这是为了避免混淆,因为Ruby解释器会自动创建一个符号时,它解析红宝石功能,如解释在这里.