我指的是Ruby Koans https://github.com/edgecase/ruby_koans/blob/master/src/about_symbols.rb#L26的about_symbols.rb中的这个测试
def test_method_names_become_symbols
symbols_as_strings = Symbol.all_symbols.map { |x| x.to_s }
assert_equal true, symbols_as_strings.include?("test_method_names_become_symbols")
end
# THINK ABOUT IT:
#
# Why do we convert the list of symbols to strings and then compare
# against the string value rather than against symbols?
为什么我们必须首先将该列表转换为字符串?
发布于 2011-01-14 06:40:18
因为如果你这样做了:
assert_equal true, all_symbols.include?(:test_method_names_become_symbols)
它可能(取决于你的ruby实现)自动为真,因为:test_method_names_become_symbols
创建了这个符号。参见this bug report。
发布于 2013-11-13 19:11:29
上面的两个答案都是正确的,但鉴于Karthik上面的问题,我想我应该发布一个测试,演示如何准确地将符号传递给include
方法
def test_you_create_a_new_symbol_in_the_test
array_of_symbols = []
array_of_symbols << Symbol.all_symbols
all_symbols = Symbol.all_symbols.map {|x| x}
assert_equal false, array_of_symbols.include?(:this_should_not_be_in_the_symbols_collection) #this works because we stored all symbols in an array before creating the symbol :this_should_not_be_in_the_symbols_collection in the test
assert_equal true, all_symbols.include?(:this_also_should_not_be_in_the_symbols_collection) #This is the case noted in previous answers...here we've created a new symbol (:this_also_should_not_be_in_the_symbols_collection) in the test and then mapped all the symbols for comparison. Since we created the symbol before querying all_symbols, this test passes.
end
关于Koans的附加说明:如果您不理解任何内容,请使用puts
语句和自定义测试。例如,如果您看到:
string = "the:rain:in:spain"
words = string.split(/:/)
如果不知道words
可能是什么,请添加下面这行
puts words
并在命令行中运行rake
。同样,像我在上面添加的测试在理解Ruby的一些细微差别方面也很有帮助。
https://stackoverflow.com/questions/4686097
复制相似问题