Ruby Koans #75 test_constants_become_symbols,正确答案? [英] Ruby Koans #75 test_constants_become_symbols, correct answer?

查看:22
本文介绍了Ruby Koans #75 test_constants_become_symbols,正确答案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题基于这个问题:Ruby Koan:常量成为符号.我有以下代码:

My question builds upon this question: Ruby Koan: Constants become symbols. I have the following code:

in_ruby_version("mri") do
  RubyConstant = "What is the sound of one hand clapping?"
  def test_constants_become_symbols
    all_symbols = Symbol.all_symbols

    assert_equal __, all_symbols.include?(__)
  end
end

正确答案是否应该如下?

Is the correct answer supposed to be the following?

    assert_equal true, all_symbols.include?("RubyConstant".to_sym)

我知道我不应该这样做:

I know I shouldn't just do this:

    assert_equal true, all_symbols.include?(:RubyConstant)

因为那样我可以把任何东西放进去,它仍然是真的

because then I could put anything in there and it would still be true

    assert_equal true, all_symbols.include?(:DoesNotMatter)

提前为您提出简单的是或否"问题表示歉意.我很好奇想知道正确"的答案是什么.我更愿意在我上面提到的上一篇文章的评论中提出这个问题,但我不能不单独发表一篇文章.

Apologies in advance for asking simple a "yes or no" question. I was curious as to know what the "right" answer is. I would have preferred to just ask this question in the comments in the previous post I mentioned above but I couldn't without making a separate post.

推荐答案

注意:以下答案仅适用于 irb 等环境,其中 Ruby 代码逐行执行.在执行文件中的代码时,Ruby 在执行任何操作之前都会扫描整个文件中的符号,因此以下细节不准确.我没有删除这个答案,因为它暴露了一个有趣的边缘情况,但请参阅 @GlichMr 的答案以获得更好的解释问题.

NOTE: the following answer only applies to environments like irb, where Ruby code is being executed line by line. When executing code in a file, Ruby scans the entire file for symbols before executing anything, so the following details are not accurate. I've not deleted this answer because it exposes an interesting edge case, but see @GlichMr's answer for a better explanation of the problem.

您可以安全地执行以下操作,因为 Symbol.all_symbols 返回符号数组的副本,而不是引用.

You can safely do the following, because Symbol.all_symbols returns a copy of the array of symbols, not a reference.

assert_equal true, all_symbols.include?(:RubyConstant)

我认为这是对公案的预期答案,这就是定义 all_symbols 而不是直接调用 Symbol.all_symbols 的原因.有关一些证据,请参阅以下内容:

I think that is the intended answer to the koan, and it's why all_symbols is defined rather than calling Symbol.all_symbols directly. For some evidence, see the following:

>> X = 1
=> 1
>> all_symbols = Symbol.all_symbols; nil
=> nil
>> Y = 2
=> 2
>> all_symbols.include?(:X)
=> true
>> all_symbols.include?(:Y)
=> false

使用 String#to_sym 可以直接针对 Symbol.all_symbols 进行这些调用,但不是解决这个公案所必需的.

Using String#to_sym would make it possible to make these calls against Symbol.all_symbols directly, but is not necessary for solving this koan.

这篇关于Ruby Koans #75 test_constants_become_symbols,正确答案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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