tags:

views:

63

answers:

2

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

+2  A: 

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.

sepp2k
A: 

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"
sarnold
This would also remove three leading zeros or one leading zero.
sepp2k
True sepp2k, I forgot that. :)
sarnold