0

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.

1
  • 1
    Note that you can use array decomposition inside blocks if the array is the sole block argument. aux.map {|k| [k[0],k[1].prepend("1234")]} could be written as aux.map {|k,v| [k,v.prepend("1234")]} Commented Jul 3, 2020 at 14:26

1 Answer 1

2

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]}"]}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.