Remove character from string if it starts with that character?

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

string.sub!(/^1/, '')

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


As of Ruby 2.5 you can use delete_prefix or delete_prefix! to achieve this in a readable manner.

In this case "1hello world".delete_prefix("1").

More info here:

https://blog.jetbrains.com/ruby/2017/10/10-new-features-in-ruby-2-5/

https://bugs.ruby-lang.org/issues/12694

'invisible'.delete_prefix('in') #=> "visible"
'pink'.delete_prefix('in') #=> "pink"

N.B. you can also use this to remove items from the end of a string with delete_suffix and delete_suffix!

'worked'.delete_suffix('ed') #=> "work"
'medical'.delete_suffix('ed') #=> "medical"

https://bugs.ruby-lang.org/issues/13665

I've answered in a little more detail (with benchmarks) here: What is the easiest way to remove the first character from a string?

Tags:

String

Ruby