Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of array element which is being referenced in a .each loop?

Tags:

arrays

ruby

How do I get the following to happen: I want to change the value of an array element which is being referenced between pipe characters in a .each loop.

Here is an example of what I want to do, but is not currently working:

x = %w(hello there world) x.each { |element|    if(element == "hello") {        element = "hi" # change "hello" to "hi"    } } puts x # output: [hi there world] 

It's hard to look up something so general.

like image 467
Derek Avatar asked Apr 13 '11 08:04

Derek


People also ask

Can you modify array in forEach?

Note that foreach does not modify the internal array pointer, which is used by functions such as current() and key(). It is possible to customize object iteration. In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

How do you change the value of an already established 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.

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

The forEach() loop takes the user defined function as on argument. This function has three parameters including the optional parameters. The first parameter is the value of the array which is to be updated while using in the forEach loop.


1 Answers

You can get the result you want using collect! or map! to modify the array in-place:

x = %w(hello there world) x.collect! { |element|   (element == "hello") ? "hi" : element } puts x 

At each iteration, the element is replaced into the array by the value returned by the block.

like image 191
SirDarius Avatar answered Oct 22 '22 21:10

SirDarius