# Weird thing with gsub!

**URL:** <https://www.ruby-forum.com/t/weird-thing-with-gsub/86365>\
**Category:** Ruby\
**Created:** [February 21, 2007, 7:10pm UTC](https://www.ruby-forum.com/t/weird-thing-with-gsub/86365 "2007-02-21T19:10:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![niceview](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/ba8739/32.png) [@niceview](https://www.ruby-forum.com/u/niceview)\
**Post date:** [February 21, 2007, 7:10pm UTC](https://www.ruby-forum.com/t/weird-thing-with-gsub/86365/1 "2007-02-21T19:10:30Z")

</div>

I’d like to show you some example.

–

def t1(str)  
str = str.gsub(/1/, “!”)  
end

def t2(str)  
str.gsub!(/1/, “!”)  
end

a = “123”  
p t1(a) # =\> “!23”  
p a # =\> “123”

a = “123”  
p t2(a) # =\> “!23”  
p a # =\> “!23”

–

Is ‘str’ variable a local variable in ‘t2’ method?

Why ‘str.gsub!(/1/, “!”)’ change ‘a’ variable?

---

<div class="post-metadata">

**Author:** ![niceview](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/ba8739/32.png) [@niceview](https://www.ruby-forum.com/u/niceview)\
**Post date:** [February 21, 2007, 7:18pm UTC](https://www.ruby-forum.com/t/weird-thing-with-gsub/86365/2 "2007-02-21T19:18:31Z")

</div>

Alle mercoledì 21 febbraio 2007, niceview ha scritto:

> end
> 
> Is ‘str’ variable a local variable in ‘t2’ method?
> 
> Why ‘str.gsub!(/1/, “!”)’ change ‘a’ variable?

Because gsub! changes its argument. While str is a local variable in t2,  
the  
object it references is the same that a references. You can see this  
adding  
the line

puts str.object\_id

in the definition of t2 and the line

puts a.object\_id

after a=‘123’. You’ll see that str and a are the same thing.

I hope this helps

Stefano
