似乎您实际上是在尝试将每个字符串变成一个符号。如果是这种情况,运行 each 方法将简单地忽略任何 's'。要查看工作解决方案中实际发生的情况,让我们首先分解您的解决方案。
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = []
strings.each do |x|
#So, if x is equal to a Class String of S
if x =='s'
#Turn that x into a symbol, which none of them should work
x.to_sym!
symbols.push(x)
end
end
这是你说的代码有效。
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = []
#Similar each loop, but they used s and not x
strings.each do |s|
#Instead of checking whether there is a Class String of S, it is just
#turning each value in the array into a symbol and pushing to the
#symbols array
s= s.to_sym
symbols.push(s)
end
因此,总而言之,除非's'
数组中有一个,否则您的代码将永远无法工作,其中可能有 s,但没有一个带有 s 的字符串。后者之所以有效,是因为它在没有 if 语句的情况下全部更改了它们。
-edit- 我从代码学院查看了问题,我可以看到混淆来自哪里,这就是这条指令For each s in strings, use .to_sym to convert s to a symbol.
这有点令人困惑的伪代码,但让我重新格式化它,这样你就可以看到混淆发生在哪里,strings.each |s| { s = s.to_sym }
所以目标是使用s
作为你的空变量。您不需要检测s
,只需将其用作空变量即可。