首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Ruby Koans:为什么要将符号列表转换为字符串

Ruby Koans:为什么要将符号列表转换为字符串
EN

Stack Overflow用户
提问于 2011-01-14 06:33:08
回答 2查看 10.9K关注 0票数 91

我指的是Ruby Koans https://github.com/edgecase/ruby_koans/blob/master/src/about_symbols.rb#L26的about_symbols.rb中的这个测试

代码语言:javascript
复制
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?

为什么我们必须首先将该列表转换为字符串?

EN

回答 2

Stack Overflow用户

发布于 2011-01-14 06:40:18

因为如果你这样做了:

代码语言:javascript
复制
assert_equal true, all_symbols.include?(:test_method_names_become_symbols)

它可能(取决于你的ruby实现)自动为真,因为:test_method_names_become_symbols创建了这个符号。参见this bug report

票数 83
EN

Stack Overflow用户

发布于 2013-11-13 19:11:29

上面的两个答案都是正确的,但鉴于Karthik上面的问题,我想我应该发布一个测试,演示如何准确地将符号传递给include方法

代码语言:javascript
复制
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语句和自定义测试。例如,如果您看到:

代码语言:javascript
复制
string = "the:rain:in:spain"
words = string.split(/:/)

如果不知道words可能是什么,请添加下面这行

代码语言:javascript
复制
puts words

并在命令行中运行rake。同样,像我在上面添加的测试在理解Ruby的一些细微差别方面也很有帮助。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4686097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档