Ruby - how to set the element value for an array of array element

79 views Asked by At

If I have an array with five empty arrays inside of it i.e.

`5_empty_arrays = [[], [], [], [], []]`

how would I insert a name into the 1st array of the overall array i.e.

`[["Dean"], [], [], [], []]`

?

I can currently get

`5_empty_arrays.insert[0, "Dean"]`

`[["Dean"], [], [], [], [], []]`

but that adds an extra array it doesn't insert into the 1st array.

I followed the advice of Steen slag and made the changes to my existing code but I now get "Dean" printed in every element. However, when I manually create the array of arrays as Steen slag did it works as predicted. Any idea? Thanks!

number_of_groups = 5

array = []
array = array.push([])* number_of_groups
array[0] << "Dean"
p array

=> [["Dean"], ["Dean"], ["Dean"], ["Dean"], ["Dean"]]
4

There are 4 answers

3
Michael Durrant On

You were inserting an element (hence the new array element) but you just want to set it

irb

> arrays = [[],[],[],[],[]]
=> [[], [], [], [], []]

irb> arrays[0][0]='a'
=> "a"

irb> arrays
=> [["a"], [], [], [], []]

To preserve any existing values you could use:

> arrays[0][0]='a'
=> "a"
    
> arrays
=> [["a"], [], [], [], []]
    
> existing = arrays[0][0]
=> "a"
    
> newbie = [existing, 'newnew']
=> ["a", "newnew"]
    
> arrays[0] = newbie
=> ["a", "newnew"]
    
> arrays
=> [["a", "newnew"], [], [], [], []]
0
Ben Stephens On

You probably want to select the first inner array first. You could do this with 5_empty_arrays[0] or at().

e.g.

> five_empty_arrays = [['a', 'b'], [], [], [], []]
=> [["a", "b"], [], [], [], []]
> five_empty_arrays[0].insert(0, "Dean")
=> ["Dean", "a", "b"]
> five_empty_arrays
=> [["Dean", "a", "b"], [], [], [], []]

If you wanted to add to the end of the inner array you could use push() instead of insert().

> five_empty_arrays = [['a', 'b'], [], [], [], []]
=> [["a", "b"], [], [], [], []]
> five_empty_arrays[0].push("Dean")
=> ["a", "b", "Dean"]
> five_empty_arrays
=> [["a", "b", "Dean"], [], [], [], []]
0
steenslag On
five_empty_arrays = [[], [], [], [], []]
five_empty_arrays[0] << "Dean"
five_empty_arrays[0] << "John"

p five_empty_arrays # => [["Dean", "John"], [], [], [], []]
0
user1934428 On

why not simply doing a

array[0].unshift 'Dean'

? This would work even if array[0] is a non-empty array.