将字符串转换为符号并将它们“.push”到数组中

Converting strings to symbols and ".push"ing them into an array

这是来自 Codecademy 的课程,我知道有人在这里问过这个问题,但我特别想看看我的解决方案有什么问题。以下是他们的开头:

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]

# Add your code below!

说明如下:

We have an array of strings we'd like to later use as hash keys, but we'd rather they be symbols.

Create a new variable, symbols, and store an empty array in it. Use .each to iterate over the strings array. For each s in strings, use .to_sym to convert s to a symbol and use .push to add that new symbol to symbols.

我很抱歉,格式没有完全复制,但你明白了。
这是我的解决方案:

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]

# Add your code below!

symbols = []
strings.each do |s|
    s.to_sym
    symbols.push(s)
end

提交后,我收到错误消息,指出我没有将字符串正确转换为符号。

您可以按照说明建议将其映射并存储到新变量中:

symbols = strings.map{ |str| str.to_sym }

编辑:

s.to_sym returns 一个符号,但您不会将其存储在任何地方或保存更改,因此是一种非破坏性方法。相反,您应该在返回的语句中使用 push,因此您使用 s.to_sym 作为推入新数组 symbols 的参数。调用 symbols 数组时,它现在应该包含您之前翻译成符号的所有字符串。

strings.each {|s| symbols.push(s.to_sym) }

您从 s 指向的字符串创建了一个新符号,但您没有更改 s(它仍然是一个字符串)并且您没有使用新符号。相反,你的循环应该包含代码

symbols.push(s.to_sym)

请注意,该问题要求您使用 .each,因此建议 .map 的答案是错误的,尽管它是实现相同内容的更好方法。

s.to_sym 确实将其转换为符号,但 s 仍然是一个字符串。您没有像 s = s.to_syms.to_sym! 那样再次将其分配给 s。所以你基本上推 s 字符串而不是符号。

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols=[]
strings.each do |word|
   word.downcase!
     if word.include? "s"
    symbols.push("s".to_sym)
   end
end
print symbols