FrankDrebbin
FrankDrebbin

Reputation: 135

Using .map with a nested two-dimensional array

I have a nested array, like this:

aux = [["None", ""],["Average", "avg"],["Summation", "sum"],["Maximum", "max"],["Minimum", "min"],["Count", "count"],["Distinct Count", "distinctCount"],["Max Forever", "maxForever"],["Min Forever","minForever"],["Standard Deviation","stddev"]]

Now, what i want to do, is to append "1234" (it's an example) to the beginning of the second element of each array, but not on the original array, like this:

new_aux = aux.map {|k| [k[0],k[1].prepend("1234")]}

Problem is that with this, the original array is being changed. I was reading about this and the problem seems to be the manipulation of the string, because if i convert that element to symbol, for example, the original array its not changed, like i want, but i don't exactly get what is the problem here and how should i do this.

By doing this, in new_aux i get:

[["None", "1234"],
 ["Average", "1234avg"],
 ["Summation", "1234sum"],
 ["Maximum", "1234max"],
 ["Minimum", "1234min"],
 ["Count", "1234count"],
 ["Distinct Count", "1234distinctCount"],
 ["Max Forever", "1234maxForever"],
 ["Min Forever", "1234minForever"],
 ["Standard Deviation", "1234stddev"]]

Which is what i want, the thing is that i have the exact same thing in the original array, which is what i don't want.

Upvotes: 0

Views: 321

Answers (1)

Yakov
Yakov

Reputation: 3191

prepend mutates a string itself, so using this method you change the source array. Use strings interpolation to achieve your goal new_aux = aux.map {|k| [k[0],"1234#{k[1]}"]}

Upvotes: 2

Related Questions