Forum: Ruby weird thing with gsub!

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Cfb917d2fb37a9509609c823ce3eaeed?d=identicon&s=25 niceview (Guest)
on 2007-02-21 19:10
(Received via mailing list)
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?
C40020a47c6b625af6422b5b1302abaf?d=identicon&s=25 Stefano Crocco (crocco)
on 2007-02-21 19:18
(Received via mailing list)
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
This topic is locked and can not be replied to.