arrays - Ruby中的数组问题
问题描述
我创建一个数组并编辑值:
arr = Array.new(6, Array.new(2, '0'))
arr[0][0] = 'name'
arr[1][0] = 'id'
arr[2][0] = 'type'
arr[3][0] = 'sum'
arr[4][0] = 'partner'
arr[5][0] = 'time'
之后我有这个数组:
[["time", "0"], ["time", "0"], ["time", "0"], ["time", "0"], ["time", "0"], ["time", "0"]]
当我需要这个时:
[["name", "0"], ["id", "0"], ["type", "0"], ["sum", "0"], ["partner", "0"], ["time", "0"]]
我做错了什么?
解决方案
根据 Ruby 数组文档:
http://ruby-doc.org/core-2.5.1/Array.html
Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.
这解释了为什么
arr[0][0] = 'name'
将所有键设置为相同的值。在你的情况下,最后一个获胜,所以它time
你真正想要达到什么目的?设置默认值?如果是这样,请使用块语法来预填充您的数组,例如:
arr = Array.new(6) { [2, '0'] }
推荐阅读
- python - python中的git命令,无法识别有效的git
- excel - 识别列中前一个单元格值仅在可见范围内不同的行号
- csv - .CSV 文件是否由 Spark 并行分解和处理
- ios - 添加子视图后UIButton无法点击
- javascript - 如何在js中访问id样式的属性
- r - 如何使用 dplyr 根据另一列中的值选择列?
- javascript - 当 Arduino 向 NW.js 发送空的 ArrayBuffer 时该怎么办?
- android - android.widget.Toolbar 不能强制转换为 androidx.appcompat.widget.Toolbar 即使不是这样
- asp.net-core - Serilog 过滤器表达式无法排除给定的端点日志
- amazon-web-services - AWS ElasticSearch 查询关键字没有得到我期望的结果