vinhboy
vinhboy

Reputation: 13

About Ruby Gsub

params[:hello] # => "Some params value"

hello = params[:hello]
hello.gsub!("whatever","")

params[:hello] # => ""

I don't understand, can someone please explain why the params[:hello] gets modified by the gsub! ? I expected the hello string to be modified, but not the params hash.

Upvotes: 1

Views: 375

Answers (3)

johannes
johannes

Reputation: 7272

There are two versions of String#gsub available

a= "abc" # => "abc"
b= a.gsub("b", "2") # "a2c"
a # => "abc"
c= a.gsub!("c", "3") # => "ab3"
a # => "ab3"

String#gsub! modifies the original string and returns a reference to it. String#gsub does not modify the original and makes the replacement on a copy.

It is a common ruby idiom to name methods which modify the object with a !.

Upvotes: 2

sepp2k
sepp2k

Reputation: 370102

hello and params[:hello] are references to the same string. In ruby (as in java and python among others) assignment does not copy the value, it just stores another reference to the same value in the assigned-to variable. So unless you explicitly copy the string before modifying it (using dup) any changes to the string will affect all other references to the string.

Upvotes: 6

Geo
Geo

Reputation: 96767

If you don't want it to be modified, you need to clone it, like:

hello = params[:hello].clone

The way you're doing it now, you have a reference to it, not a copy.

Upvotes: 1

Related Questions