Swapy
Swapy

Reputation: 11

Adding element at a particular index in a multi-dimensional array in ruby

When I attempt the .insert(index,element) logic with multi dimensional array:

expected_array[row][col].insert(1,score.to_s.concat("%"))

in the loop of each row where score =73 ,

I get output as:

["M73%axi's", 25, "03/06/2012"] 

when my expected result has to be:

["Maxi's", "73%", 25, "03/06/2012"] 

What am I doing wrong?

Upvotes: 0

Views: 269

Answers (1)

Shoe
Shoe

Reputation: 76240

What am I doing wrong?

You have a bidimensional array there and what expected_array[row][col] does is get to a specific element. So that you are calling String#insert (of the element) instead of Array#insert (of the inner array).

What you want instead is to select the row and call Array#insert on the column array:

expected_array[row].insert(col,score.to_s.concat("%"))

Upvotes: 2

Related Questions