Trimming leading zeros

Is there any function in ruby which allows you to trim leading zeros (or
any specific character) from a string. Or if there is some reg
expression that i can use?

···

--
Posted via http://www.ruby-forum.com/.

Hi,

for simple character replacement, you may do something like
"####helloworld".gsub!(/^#+/,'')
the same can be written in String class if you use this too often,
class String
    def trim_lead(n)
        self.gsub!(/^#{n}+/,'')
    end
end
puts "00001234".trim_lead("0")

but when you use this to replace any special characters used
internally by regex (for e.g., $)
you have to do something like "$$$1234".trim_lead("\\$")
Others may suggest better ways.

···

On Dec 29, 5:00 pm, Dipesh Batheja <dipesh_bath...@yahoo.com> wrote:

Is there any function in ruby which allows you to trim leading zeros (or
any specific character) from a string. Or if there is some reg
expression that i can use?
--
Posted viahttp://www.ruby-forum.com/.

Dipesh Batheja wrote:

Is there any function in ruby which allows you to trim leading zeros (or
any specific character) from a string. Or if there is some reg
expression that i can use?

Hi
if you have string expressions like

s = 0{1,*}[1-9]* (some number with leading zeros)

perhaps the must obvious method is

s.to_i.to_s

:slight_smile:

but this isn't genralizable to other kind of leading characters,
for them a regexp may be better

Tom

The simplest and fastest is probably

s.sub! /\A0+/, ''

Kind regards

  robert

···

On 29.12.2007 13:00, Dipesh Batheja wrote:

Is there any function in ruby which allows you to trim leading zeros (or
any specific character) from a string. Or if there is some reg
expression that i can use?