Weird thing with gsub!

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?

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