【问题标题】:What to learn from Ruby Koan nº 75?从 Ruby Koan nº 75 可以学到什么?
【发布时间】:2012-11-08 04:18:26
【问题描述】:

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”到底能学到什么?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    在 ruby​​ 中,以大写字母开头的变量变为constants。 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​​ 函数时会自动创建一个符号,如 here 所述。

    【讨论】:

    • 哇,谢谢!这些常量是范围有限的,对吧?或者它是一种全球性的东西?
    • 由于RubyConstant 是在AboutSymbols 类中定义的,因此它绑定到该范围,您必须使用::AboutSymbols::RubyConstant 在全局级别通过范围运算符访问它。阅读更多关于 ruby​​ 常量的信息 here。另外,请查看 AboutConstants 中的 koans。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2011-04-29
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    相关资源
    最近更新 更多