gpt4 book ai didi

arrays - 将字符串转换为符号并将它们 ".push"转换为数组

转载 作者:太空宇宙 更新时间:2023-11-03 17:47:21 24 4
gpt4 key购买 nike

这是来自 Codecademy 的类(class),我知道有人在这里问过这个问题,但我特别想看看我的解决方案有什么问题。这是他们让你开始的:

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

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

最佳答案

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

symbols.push(s.to_sym)

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

关于arrays - 将字符串转换为符号并将它们 ".push"转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33380176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com