shin
shin

Reputation: 32721

How to find if input has 0s at the beginning in Ruby

I want to detect if input has 0 at the beginning and erase them. I came up the following code. But this detect 0 anywhere in input. How can I change this to detect 0s at the beginning?

if input.include?("0") 
    @input = input.gsub(/^0+/,"")  
end

Upvotes: 0

Views: 54

Answers (1)

Vitor Tyburski
Vitor Tyburski

Reputation: 1072

I think it is simplier to:

...my_string.start_with? "0"...

if it is not a string, simply cast it before (to_s). But there are other methods like:

...my_string.match(/\A0/)... 

Or:

...if (my_string[0] == "0") ....

In cases that your string is multiline, all these method wil match the first character of the String. If you want to match any 0 on start of any line

...my_string.match(/^0/)... 

Upvotes: 3

Related Questions