二维数组,推到一个阵列显示在所有阵列? [英] 2d array, pushing to one array shows up in all arrays?

查看:215
本文介绍了二维数组,推到一个阵列显示在所有阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的红宝石,所以我清楚误解的东西。我意欲创建大小2,其中每个元件本身是一个阵列,然后推项的一个或另一个子阵列的阵列

I'm new to ruby so I'm clearly misunderstanding something. I intended to create an array of size 2, where each element is itself an array, then push items to one or the other sub-array:

#!/usr/bin/env ruby
arr = Array.new(2, Array.new)

puts 'default, no entries:'
arr.each_with_index { |a, i| puts 'arr[' + i.to_s + '] = ' + a.to_s }
puts ''

puts 'adding "kitty" to arr[0]:'
arr[0].push('kitty') # add an element to the sub-array at arr[0]
arr.each_with_index { |a, i| puts 'arr[' + i.to_s + '] = ' + a.to_s }
puts ''

puts 'adding "doggy" to arr[1]:'
arr[1].push('doggy') # add an element to the sub-array at arr[1]
arr.each_with_index { |a, i| puts 'arr[' + i.to_s + '] = ' + a.to_s }

输出:

default, no entries:
arr[0] = []
arr[1] = []

adding "kitty" to arr[0]:
arr[0] = ["kitty"]
arr[1] = ["kitty"]

adding "doggy" to arr[1]:
arr[0] = ["kitty", "doggy"]
arr[1] = ["kitty", "doggy"]

我希望改编[0] .push()在ARR添加的元素[0] [0],是错了吗?

I would expect arr[0].push() to add the element at arr[0][0], is that wrong?

推荐答案

ARR = Array.new(2 Array.new)分配阵列两个新的对象。

arr = Array.new(2, Array.new) assigns the same array to both of the new objects.

如果您使用的是块而不是形式,你会为你期望得到两个单独的数组:

If you use a block form instead, you'll get two separate arrays as you expect:

arr = Array.new(2) { Array.new }

这篇关于二维数组,推到一个阵列显示在所有阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆