Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing entry in an array while looping through it

Tags:

arrays

ruby

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?

like image 741
pingu Avatar asked Feb 21 '11 08:02

pingu


People also ask

How do you change an element in an array?

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.

How do you go through an array while loop?

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.

Can the elements of an array be updated using a forEach loop?

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.

What is looping through an array called?

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.


Video Answer


1 Answers

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.

like image 83
sflinter Avatar answered Oct 15 '22 16:10

sflinter