Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby weird assignment behaviour

Tags:

ruby

Is this a ruby bug?

target_url_to_edit = target_url

if target_url_to_edit.include?("http://")
  target_url_to_edit["http://"] = ""
end

logger.debug "target url is now #{target_url}"

This returns target_url without http://

like image 510
jaycode Avatar asked Aug 11 '26 16:08

jaycode


2 Answers

You need to duplicate the in-memory object because variable names are just references to in-memory objects:

target_url_to_edit = target_url.dup

Now target_url_to_edit gets assigned a new copy of the original object.

For your case this code probably does the same in just one line (no dup, no if):

target_url_to_edit = target_url.sub(%r{^http://}, "")
like image 193
hurikhan77 Avatar answered Aug 13 '26 09:08

hurikhan77


No, this is not a bug in Ruby, this is just how shared mutable state works, not just in Ruby but in any programming language.

Think about it this way: my mom calls me "son", my friends call me "Jörg". If I cut my hair, then it doesn't matter which name you use to refer to me: I am the same person, regardless of whether you call me "son" or "Jörg" or "Mr. Mittag" or "hey, douchebag", therefore my hair will always be short. It doesn't magically grow back if you call me by a different name.

The same thing happens in your code: you refer to the string by two different names, but it doesn't matter which name you use; if the string changes, then it changes.

The solution is, of course, to not share mutable state and to not mutate shared state, like in @hurikhan77's answer.

like image 23
Jörg W Mittag Avatar answered Aug 13 '26 09:08

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!