首页 > 解决方案 > 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"]]

我做错了什么?

标签: arraysruby

解决方案


根据 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'] }

推荐阅读