Ruby Koans:为什么将符号列表转换为字符串 [英] Ruby Koans: Why convert list of symbols to strings

查看:53
本文介绍了Ruby Koans:为什么将符号列表转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm referring to this test in about_symbols.rb in Ruby Koans https://github.com/edgecase/ruby_koans/blob/master/src/about_symbols.rb#L26

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?

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

Why exactly do we have to convert that list into strings first?

推荐答案

这与符号的工作方式有关.对于每个符号,实际上只有一个符号存在.在幕后,符号只是一个由名称(以冒号开头)引用的数字.因此,当比较两个符号的相等性时,您比较的是对象标识和不是引用该符号的标识符的内容.

This has to do with how symbols work. For each symbol, only one of it actually exists. Behind the scenes, a symbol is just a number referred to by a name (starting with a colon). Thus, when comparing the equality of two symbols, you're comparing object identity and not the content of the identifier that refers to this symbol.

如果您要进行简单的测试 :test == "test",它将是错误的.因此,如果要将迄今为止定义的所有符号收集到一个数组中,则需要先将它们转换为字符串,然后再进行比较.您不能以相反的方式执行此操作(首先将要比较的字符串转换为符号),因为这样做会创建该符号的单个实例并使用您正在测试是否存在的符号污染"您的列表.

If you were to do the simple test :test == "test", it will be false. So, if you were to gather all of the symbols defined thus far into an array, you would need to convert them to strings first before comparing them. You can't do this the opposite way (convert the string you want to compare into a symbol first) because doing that would create the single instance of that symbol and "pollute" your list with the symbol you're testing for existence.

希望有所帮助.这有点奇怪,因为您必须测试符号是否存在,而不会在测试期间意外创建该符号.您通常不会看到这样的代码.

Hope that helps. This is a bit of an odd one, because you have to test for the presence of a symbol without accidentally creating that symbol during the test. You usually don't see code like that.

这篇关于Ruby Koans:为什么将符号列表转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆