veccy
veccy

Reputation: 925

check number and remove leading zeros

I want to check a variable in ruby to see if it has two leading zeros (00) If it does the 00 should be removed

How can this be done

Upvotes: 26

Views: 27390

Answers (5)

richardun
richardun

Reputation: 713

OP clearly asked for removing two zeros, but a note for others that are interested in removing all leading zeros and might not be as strong in regular expressions, you can do that with this instead:

str.sub!(/^[0]+/,'')

The + is a regex special character that applies to 1 or more.

Upvotes: 42

Ashik Salman
Ashik Salman

Reputation: 1879

Ruby 2.5

str.delete_prefix("00") # Delete exactly two zeros

Upvotes: 3

Paulo Tarud
Paulo Tarud

Reputation: 586

  • ^ means start with
  • * means zero or more

str.sub!(/^0*/, '')

That regexp can be used with "1234", "01234", "001234", "0001234", etc.

Upvotes: 8

sarnold
sarnold

Reputation: 104050

It's pretty easy to convert to an integer and convert back to a string:

irb(main):007:0> s="009" ; s.to_i.to_s
=> "9"
irb(main):008:0> s="004" ; s.to_i.to_s
=> "4"
irb(main):009:0> s="00999" ; s.to_i.to_s
=> "999"

or, for floats:

irb(main):003:0> s="000.45" ; s.to_f.to_s
=> "0.45"

Upvotes: 34

sepp2k
sepp2k

Reputation: 370112

If you're talking about strings:

str.sub!(/^00/, "")

The regex /^00/ matches if the string starts with two zeros. sub! will then take the match (the two zeros) and replace them with the empty string.

Upvotes: 29

Related Questions