在about_symbols.rb Ruby Koan(https://github.com/edgecase/ruby_koans)中,我有以下代码:
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?(:"nonexistent")
assert_equal true, all_symbols.include?(:"What is the sound of one hand clapping?")
assert_equal true, all_symbols.include?("What is the sound of one hand clapping?".to_sym)
end
Run Code Online (Sandbox Code Playgroud)
按原样,测试通过.
三个问题:
为什么第一个断言通过?:"nonexistent"不应该包含在all_symbols中,但它包括在内,所以我必须误解一些东西.
当我注释掉第二个断言时,测试失败,因为"What is the sound of one hand clapping?".to_sym不包括在all_symbols中,:"What is the sound of one hand clapping?"而是包括在内.既然它们是等价的,为什么最后一个断言失败了?另外,为什么第二个断言未被注释时它会通过?(为什么第二个断言对第三个断言有影响?)
据我所知,这个Ruby Koan的目的是证明常量成为符号(至少,这是我从方法名称推断的).由于RubyConstant是一个带值的常量"What is the sound of one hand clapping?",为什么不"What is the …