【发布时间】:2011-07-18 12:58:36
【问题描述】:
在 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
按原样,测试通过了。
三个问题:
为什么第一个断言通过了?
:"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 sound of one hand clapping?".to_sym不包含在符号列表中?我能想到的唯一解释是,与方法名相反,常量实际上并没有成为符号。
感谢您的帮助!
【问题讨论】:
-
这里提出了同样的问题:stackoverflow.com/questions/13295776/…