trimming leading zeros

D

Dipesh Batheja

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?
 
Y

Young Moon

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,

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.
 
T

Tomaso Tosolini

Dipesh said:
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

:)

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

Tom
 
R

Robert Klemme

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top