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?
To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.
You can iterate over the elements of an array in Java using any of the looping statements. To access elements of an array using while loop, use index and traverse the loop from start to end or end to start by incrementing or decrementing the index respectively.
forEach does not modify the array itself, the callback method can. The method returns undefined and cannot be chained like some other array methods. forEach only works on arrays, which means you need to be a little creative if you want to iterate over objects.
We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.
When you're inside the arr.each
block, the colour
variable is bound to one of the objects in the arr
array.
However, as soon as you make the assignment colour = "green"
in the block, now the colour
variable is bound to a new object (namely a String with a value of "green"
), and the original arr
remains unaffected.
One way to achieve what you're talking about would be:
arr.each_index do |i|
arr[i] = "green" if arr[i] == "red"
end
which manipulates the array directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With