[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

weird thing with gsub!

niceview

2/21/2007 6:07:00 PM

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?

1 Answer

Stefano Crocco

2/21/2007 6:17:00 PM

0

Alle mercoledì 21 febbraio 2007, niceview ha scritto:
> 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?

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