Reputation: 1
When I run a regex trying to remove an initial zero from a number as in the example I get the correct answer if there is a zero before the number. However, if there are no zeroes I get an empty string.
This is not the expected result for me, but might be the way things work.
I would like to have an expression that keeps the string intact if there are no initial zeroes.
This is MRI Ruby 2.6.1
Example 1
string = "0067 more text"
puts string[0..3].sub!(/^0+/, "")
#=> 67
Example 2
string = "6776 more text"
puts string[0..3].sub!(/^0+/, "")
#=> 'empty string'
In Example 2 I would like it to keep the string intact. I wouldn't a priori expect the expression to delete the string. But if it is the correct behaviour I need a way to make it keep the original string intact.
Upvotes: 0
Views: 80
Reputation: 224904
sub!
does keep the string intact if there’s no match. It just returns nil
. If you don’t need to do the operation in place, use the non-mutating String#sub
:
puts string[0..3].sub(/^0+/, "")
If you do want the replacement done in place, you’ll be holding onto the string in practice, and it’ll work fine:
s = string[0..3]
s.sub!(/^0+/, "")
puts s
Relevant documentation for sub!
:
sub!(pattern, replacement) → str or nil
sub!(pattern) {|match| block } → str or nilPerforms the same substitution as
#sub
in-place.Returns
str
if a substitution was performed ornil
if no substitution was performed.
Upvotes: 1