在Ruby Koans的帮助下尝试Ruby。有下面的测试有:使用include检查符号是否存在于数组中?
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和正常的文件不同的结果?
谢谢!
[Ruby Koans:为什么要将符号列表转换为字符串](http://stackoverflow.com/questions/4686097/ruby-koans-why-convert-list-of-symbols-to-strings) –