1

公安コード、番号 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 では、大文字で始まる変数は定数になります。公案の目的は、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 に答える