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.
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.
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.
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.
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.
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