使用Ruby Koans学习Ruby技术。这里有一个测试如下:
def test_method_names_become_symbols
symbols_as_strings = Symbol.all_symbols.map { |x| x.to_s }
assert_equal __, 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?
我尝试在irb控制台中进行相同的操作,结果对于未定义的方法返回了“false”。但是,我在一些test.rb文件中进行了相同的操作,对于已存在和不存在的方法都返回了“true"。示例代码:
def test_method
end
symbols = Symbol.all_symbols.map { |x| x }
puts symbols.include?(:test_method) # returns true in both cases
puts symbols.include?(:test_method_nonexistant) # returns false in irb, true if executed directly
问题是:为什么在这种情况下我们要将符号转换为字符串,以及为什么在irb和普通文件中会有不同的结果?
谢谢!