加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Codecademy“符号和字符串之间的转换”ruby课程

发布时间:2020-12-16 22:06:02 所属栏目:百科 来源:网络整理
导读:这些是Codecademy的说明: 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 array,symbols. Use .each to iterate over the strings array and convert each string to a symbol,adding
这些是Codecademy的说明:

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 array,symbols. Use .each to iterate over the strings array and convert each string to a symbol,adding those symbols to symbols.

这是我写的代码(提供了字符串数组):

strings = ["HTML","CSS","JavaScript","Python","Ruby"]
symbols = []
strings.each { |x| x.to_sym }
symbols.push(strings)

我知道我可能做了多件事情,但是我已经通过了这个很远的ruby轨道,很少有困难,所以我不知道为什么这是一个令我失望的事情.首先,它不是将字符串转换为符号,其次,它不是将它们推送到符号数组.

解决方法

to_sym一个人没有做任何有用的事情;它正在转换字符串,但不存储在任何地方或稍后使用它.你想继续添加到符号数组.
strings = ["HTML","Ruby"]
symbols = []
strings.each { |s| symbols.push s.to_sym }

或者更优雅的是,您可以跳过设置符号= [],只需使用地图即可在一行中创建它:

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

地图将遍历数组中的每个项目,并根据地图函数将其转换为其他内容.对于简单应用功能的简单地图,您可以进一步了解:

symbols = strings.map &:to_sym

(这与symbols = strings.map(&:to_sym)相同,使用您觉得更有品位的人.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读