tags:

views:

549

answers:

3

How can I remove the very first "1" from any string if that string starts with a "1"?

"1hello world" => "hello world"
"112345" => "12345"

I'm thinking of doing

string.sub!('1', '') if string =~ /^1/

but I' wondering there's a better way. Thanks!

+8  A: 

Why not just include the regex in the sub! method?

string.sub!(/^1/, '')
Zach Langley
ha, you beat me by a minute +1
Gordon Wilson
+3  A: 

if you're going to use regex for the match, you may as well use it for the replacement

string.sub!(%r{^1},"")

BTW, the %r{} is just an alternate syntax for regular expressions. You can use %r followed by any character e.g. %r!^1!.

Gordon Wilson
"BTW, the %r{} syntax for regular expressions allows you to avoid escaping / within the expression." - But now you have two characters that you need to escape instead of one but the point is moot since none of the characters in question even appear in the pattern.
Robert Gamble
It's just a subjective preference. I'd argue that / is a more common character than either {}. My BTW was an explanation in case the OP hadn't seen %r{} syntax before.
Gordon Wilson
A: 

Careful using sub!(/^1/,'') ! In case the string doesn't match /^1/ it will return nil. You should probably use sub (without the bang).

No, it will *return* nil in that case, but the original string will remain unchanged. If you just use `sub`, you will have to do the longer string = string.sub(/^/, '').
Zach Langley