Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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 !.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top