[ruby-core:92934] Re: [Ruby trunk Bug#15895] String#gsub and String#sub should return original string if no substitution(s) have been made
From:
Tanguy Andreani <ruby@...>
Date:
2019-06-03 10:02:58 UTC
List:
ruby-core #92934
> IMO, it'd be great to have the original string returned if substitution(s) couldn't be made.
Sorry in advance in case I miss the point.
Wouldn’t that introduce an incompatibility with many scripts?
Say I have a string that I’m not sure if it contains html or not. So I run gsub just like you mentioned and store its result in a local variable. Then I go on working on my copy of... wait, I don’t know anymore if the string returned by gsub is a copy or not.
So my code should now resemble this to match your changes:
safestring = mystring.gsub(...)
safestring = mystring.dup if sameobject?(safestring, mystring)
Or more "simple":
safestring = mystring.gsub(...).dup
Which is clearly not cool.
I think it is better to just duplicate the string from the start and then, use the destructive alternatives in the loop. (Which I would think doesn’t quiet match your use case after looking back at your post.)
Sent via Migadu.com, world's easiest email hosting
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>