9/18 Array "unchangeable" values


#1

The instruction was to add a block after .each that multiplies each item by itself and puts the result to the console. It's not a problem did it, but i wonder how could i actually change the value of my array instead of just putting out. My program is like
my_array = [1, 2, 3, 4, 5]

my_array.each do |w|
    w = w*w
    puts w
end

it puts out to the console every number as the task asked but after the method ran i had to realize the array did not changed at all! it's still 1,2,3,4,5

my_array = [1, 2, 3, 4, 5]

my_array.each do |w|
    w = w*w
 end
 puts my_array

However logically I tought if something already happened to the values of my array it just won't become default again since my method ran. Please explain me why is that, and what is the mechanic to change the values in place.
Now the best i could think is that somehow i just return the changed values like this

my_array = [1, 2, 3, 4, 5]

my_array.each do |w|
    return w*w
 end

new_array = my_array[1, 2, 3, 4, 5]
new_array

but this isn't working. Thank you for your attention and looking forward to your answers :slightly_smiling:


#2

my_array.map! { |elem| elem * 37 }

(! is for in-place, otherwise you'd get a new array)

your w isn't in any way part of your array. It's a reference to a value in the array. Changing what it refers to does nothing to the array.