2

I make an array and edit values:

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'

And after that i have this array:

[["time", "0"], ["time", "0"], ["time", "0"], ["time", "0"], ["time", "0"], ["time", "0"]]

When i need this:

[["name", "0"], ["id", "0"], ["type", "0"], ["sum", "0"], ["partner", "0"], ["time", "0"]]

What do i do wrong?

  • See also [Creating matrix with Array.new(n, Array.new)](https://stackoverflow.com/q/22417074/479863), [Why Array.new(3, \[\]) works differently ...](https://stackoverflow.com/q/42615737/479863), and lots of others. Don't feel bad, the duplicates aren't easy to find (unless you know the answer already). – mu is too short Sep 12 '18 at 17:51

2 Answers2

1

According to the Ruby Array docs:

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.

Which explains why

arr[0][0] = 'name'

Sets all keys to the same value. In your case the last-one wins so its time

What are you really trying to achieve? Setting a default value? If so, use the block syntax to pre-fill your array, like:

 arr = Array.new(6) { [2, '0'] }
Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
  • I'm trying to make an array with pairs of values. I had the same trouble with 2-dimensional arrays in ruby everytime i set values using something like `arr[0][0] = 'name'`. I think that's the wrong way to work with 2d-arrays but i haven't found any other ways. – M. Sakovich Sep 12 '18 at 17:42
  • @M.Sakovich First of all, there are no 2D arrays in Ruby, just arrays-of-arrays; a minor point perhaps but it underlies the real problem of accidental reference sharing. If you want to make an array-of-arrays, use the block form of `Array.new` as Cody suggests: `Array.new(n) { [ ] }`. – mu is too short Sep 12 '18 at 17:54
0
arr = Array.new(6){Array.new(2,'0')}
arr[0][0] = 'pan'
arr[1][0] = 'id'
arr[2][0] = 'type'
arr[3][0] = 'sum'
arr[4][0] = 'partner'
arr[5][0] = 'time'
puts arr

Try This.

Rohit-Pandey
  • 2,039
  • 17
  • 24