# Each method

**URL:** <https://www.ruby-forum.com/t/each-method/192511>\
**Category:** Ruby\
**Created:** [August 1, 2010, 12:12am UTC](https://www.ruby-forum.com/t/each-method/192511 "2010-08-01T00:12:47Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![amiref](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/41988e/32.png) [@amiref](https://www.ruby-forum.com/u/amiref)\
**Post date:** [August 1, 2010, 12:12am UTC](https://www.ruby-forum.com/t/each-method/192511/1 "2010-08-01T00:12:47Z")

</div>

Hi  
What can I do to can apply some change to an array for always ? ( I want  
to use iterator and each method and apply some change in an array )

---

<div class="post-metadata">

**Author:** ![amiref](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/41988e/32.png) [@amiref](https://www.ruby-forum.com/u/amiref)\
**Post date:** [August 1, 2010, 3:23am UTC](https://www.ruby-forum.com/t/each-method/192511/2 "2010-08-01T03:23:49Z")

</div>

Amir E. wrote:

> Hi  
> What can I do to can apply some change to an array for always ? ( I want  
> to use iterator and each method and apply some change in an array )

if I understood the question:

array.collect! {|item| block } â†’ array  
array.map! {|item| block } â†’ array

Invokes the block once for each element of self, replacing the element  
with the value returned by block. See also Enumerable#collect.

a = [“a”, “b”, “c”, “d”]  
a.collect! {|x| x + “!” }  
a #=\> [“a!”, “b!”, “c!”, “d!”]

---

<div class="post-metadata">

**Author:** ![amiref](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/41988e/32.png) [@amiref](https://www.ruby-forum.com/u/amiref)\
**Post date:** [August 1, 2010, 1:20pm UTC](https://www.ruby-forum.com/t/each-method/192511/3 "2010-08-01T13:20:34Z")

</div>

Maurizio De Santis wrote:

> Amir E. wrote:
> 
> > Hi  
> > What can I do to can apply some change to an array for always ? ( I want  
> > to use iterator and each method and apply some change in an array )
> 
> if I understood the question:
> 
> array.collect! {|item| block } â†’ array  
> array.map! {|item| block } â†’ array
> 
> Invokes the block once for each element of self, replacing the element  
> with the value returned by block. See also Enumerable#collect.
> 
> a = [“a”, “b”, “c”, “d”]  
> a.collect! {|x| x + “!” }  
> a #=\> [“a!”, “b!”, “c!”, “d!”]

Another option, if you know the contents are all Strings or Arrays, is  
to use replace:

a.each { |x| x.replace(x+"!") }

It’s different because it modifies the string objects themselves  
(leaving the Array pointing to the same string objects)
