arr = ["red","green","blue","yellow"]
arr.each do |colour|
if colour == "red"
colour = "green"
end
end
puts arr.inspect
The above code outputs:
["red", "green", "blue", "yellow"]
but why not?
["green", "green", "blue", "yellow"]
I thought that colour was a reference to the current element in the array, and whatever i did to it would effect that array element?
When you’re inside the
arr.eachblock, thecolourvariable is bound to one of the objects in thearrarray.However, as soon as you make the assignment
colour = "green"in the block, now thecolourvariable is bound to a new object (namely a String with a value of"green"), and the originalarrremains unaffected.One way to achieve what you’re talking about would be:
which manipulates the array directly.