weird thing with gsub!

N

niceview

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"
 
S

Stefano Crocco

Alle mercoled=EC 21 febbraio 2007, niceview ha scritto:
I'd like to show you some example.

--

def t1(str)
str =3D str.gsub(/1/, "!")
end

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

a =3D "123"
p t1(a) # =3D> "!23"
p a # =3D> "123"

a =3D "123"
p t2(a) # =3D> "!23"
p a # =3D> "!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, th=
e=20
object it references is the same that a references. You can see this adding=
=20
the line=20

puts str.object_id

in the definition of t2 and the line

puts a.object_id

after a=3D'123'. You'll see that str and a are the same thing.

I hope this helps

Stefano
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,234
Messages
2,571,179
Members
47,811
Latest member
GregoryHal

Latest Threads

Top