I'm experiencing the following. I expect only the first sub-element of the first sub array to be assigned "x", not the first element of each sub array. Can anyone explain this behaviour, and perhaps how to work around it? (Note that this may well be expected behaviour, but if it is, it contradicts my expectations.)
x = Array.new(3, Array.new(5))
# => [[nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]]
x[0][0] # => nil
x[0][0] = "x"
x
# => [["x", nil, nil, nil, nil], ["x", nil, nil, nil, nil], ["x", nil, nil, nil, nil]]
workaround is :
x = Array.new(3) { Array.new(5) }
x[0][0] = 'a'
x # => [["a", nil, nil, nil, nil], [nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil]]
new(size) {|index| block }
Here an array of the given size is created. Each element in this array is created by passing the element’s index to the given block and storing the return value.
Read also Common gotchas
When sending the second parameter, the same object will be used as the value for all the array elements. Since all the Array elements store the same array Array.new(5), changes to one of them will affect them all.
If multiple copies are what you want, you should use the block version which uses the result of that block each time an element of the array needs to be initialized, as I did above.
2d_array = Array.new(rows) { Array.new(columns) }
Related
This question already has answers here:
Creating matrix with `Array.new(n, Array.new)`
(2 answers)
Closed 5 years ago.
Context: Im trying to populate a 2D array with while loops ,after witch I want to try and do it with {} block format. The point is to understand how these two syntax structures can do the same thing.
I have been reviewing this code and scouring the internet for the past hour and Ive decided that I'm simply not getting something, but I dont understand what that is.
The outcome should be
=> [["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"]
=> ..(Sequentially)..
=>["H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8"]]
The code is as follows:
char= ('A'..'H').to_a
num= (1..8).to_a
arr=Array.new(8,Array.new(8))
x=0
while x <8
y=0
while y < 8
arr[x][y] = char[x] + num[y].to_s
y+=1
end
x+=1
end
arr
Thank you in advance, I appreciate your patience and time.
####Edit####
The source of the confusion was due to a lack of understanding of the reference concept. Referencing allows us, by using the Array.new(n,Array.new(n)) method scheme, to access the values of the nested arrays that share a reference to their data via their parent array. This question is addressed directly here: Creating matrix with `Array.new(n, Array.new)` . Although I thought it was a issue with my while loops, the problem was indeed how I created the matrix.
Your code is not working due to call to reference. Ruby is pass-by-value, but all the values are references. https://stackoverflow.com/a/1872159/3759158
Have a look at the output
2.4.3 :087 > arr = Array.new(8,Array.new(8))
=> [[nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil], [nil, nil, nil, nil, nil, nil, nil, nil]]
2.4.3 :088 > arr[0][0] = 'B'
=> "B"
2.4.3 :089 > arr
=> [["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil], ["B", nil, nil, nil, nil, nil, nil, nil]]
This is happen because of call by object on array object you can see this in effect by a simple example
a = []
b = a
b << 10
puts a => [10]
and very same thing is happening with your code.
Instead of all that try this :
('A'..'H').map{|alph| (1..8).map{|num| "#{alph}#{num}"}}
If I do the following:
table = Array.new(
3,
Array.new(
3,
nil
)
)
# =>
[
[nil, nil, nil],
[nil, nil, nil],
[nil, nil, nil]
]
Now I would like to modify the value at index 2 in the second array, so I would do:
table[1][2] = 2.343
I would now expect to see:
# =>
[
[nil, nil, nil],
[nil, nil, 2.343],
[nil, nil, nil]
]
However what I'm getting is this:
[
[nil, nil, 2.343],
[nil, nil, 2.343],
[nil, nil, 2.343]
]
What am I not getting here?
PS: Running ruby 2.3
For fix with behavior, try next:
empty_table = Array.new(3) { Array.new(3) }
From array manual:
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.
you are essentially saying create an array with three elements, and put this element (the new array) in each space. The element you are putting in the first array, is just created once. The only way I know to do what you want is using a for loop to push as many new arrays into the first array as you need. something like this:
table = Array.new(1, Array.new(3, 0))
0..1.each do |i|
table.push(Array.new(3, 0)) #add two more arrays to the first dimension
end
I have an integer with a value
I want to create an array with nil values representing this integer
For example:
i = 5
# The result i want is
[nil, nil, nil, nil, nil]
What is the most Ruby way of doing this? Aka, the shortest way. Without need of looping et c.
This is very basic question:
i = 5
Array.new(i) #=> [nil, nil, nil, nil, nil]
i = 5
[nil]*i #=> [nil, nil, nil, nil, nil]
I have built a presenter class whose only job is to convert a given array into a string. I am test driving the solution, so I started with "[nil, nil, nil]" but each nil will eventually be replaced with letter. That functionality is being handled by another class.
I am trying now to build an interface whose only job is to convert that string back to an array. So I will need to convert e.g. "[\"a\", \"b\", nil]" back to ["a", "b", nil]. But I am stuck.
For example, I'd like to convert
"[nil, nil, nil]"
to
[nil, nil, nil]
How could I do it?
Just use:
eval(string)
eval("[nil, nil, nil]")
Caution:
This is a very insecure method and you have to use it only if you are completely sure that the string contains a SAFE array..
I am guessing that you are producing the string yourself on one side, for example:
arr = [nil, nil, nil]
str = arr.inspect
#=> "[nil, nil, nil]"
Whereas I would advise you to serialize the array using a format such as JSON, YAML or Ruby's built in Marshalling library.
JSON
require 'json'
arr = [nil, nil, nil]
str = JSON.dump(arr)
#=> "[null,null,null]"
JSON.load(str)
#=> [nil, nil, nil]
YAML
require 'yaml'
arr = [nil, nil, nil]
str = YAML.dump(arr)
#=> "---\n- \n- \n- \n"
YAML.load(str)
#=> [nil, nil, nil]
Marshal
arr = [nil, nil, nil]
str = Marshal.dump(arr)
#=> "\x04\b[\b000"
Marshal.load(str)
#=> [nil, nil, nil]
I tried:
1.9.3-p448 :046 > a=Array.new(7){Array.new(7)}
=> [[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil]]
1.9.3-p448 :047 > a[0,0]='a'
=> "a"
1.9.3-p448 :048 > a[0,1]='b'
=> "b"
1.9.3-p448 :049 > a[0,2]='c'
=> "c"
1.9.3-p448 :050 > a[1,0]='d'
=> "d"
1.9.3-p448 :051 > a[1,1]='e'
=> "e"
1.9.3-p448 :052 > a[1,2]='f'
=> "f"
and I got:
1.9.3-p448 :053 > a
=> ["c", "f", [nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil]]
but I wanted
1.9.3-p448 :053 > a
=> ["a","b","c",nil,nil,nil], ["d","e","f", nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil]]
In Ruby, as #Daniel points out, accessing multidimensional array elements is done as it is done in, for example, C.
The notation you're attempting to use is from, for example, Pascal, but doesn't work the way you think it does in Ruby. What it does in Ruby is give a start index and a count.
So if you have:
a = ['a','b','c','d','e','f']
Then a[2,3] will be:
['c','d','e']
This is described in the Ruby Array class documentation. If you attempt to assign to it, Ruby will dynamically change the array accordingly. In the above example, if I do this:
a[2,3] = 'h'
Then a will become:
['a','b','h','f']
Or if I do this:
a[2,0] = 'j'
Ruby inserts a value at position 2 and now I get:
['a','b','j','h','f']
In other words, assigning a value to a[2,3] replaced the subarray of three values with whatever I assigned to it. In the case of a two-dimensional array, such as in the original example,
a[0,0] = 'a' # Inserts a new first row of array with value 'a'
a[0,1] = 'b' # Replaces the entire first row of array with 'b'
a[0,2] = 'c' # Replaces the entire first two rows of array with 'c'
a[1,0] = 'd' # Inserts a new first row of array with value 'd'
a[1,1] = 'e' # Replaces the entire second row of array with 'e'
a[1,2] = 'f' # Replaces the entire second and third rows of array with 'f'
Thus, you get the result that you see.
You're currently assigning letters to a range of the outer array. This is the syntax to reference the inner arrays:
a[0][0]='a'