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?

On Dec 29, 5:00 pm, Dipesh B. [email protected] 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/.

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.

1 Like

Dipesh B. 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

On 29.12.2007 13:00, Dipesh B. 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?

The simplest and fastest is probably

s.sub! /\A0+/, β€˜β€™

Kind regards

robert