[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

trimming leading zeros

Dipesh Batheja

12/29/2007 12:00:00 PM

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

3 Answers

Young Moon

12/29/2007 12:28:00 PM

0

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

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.

Tomaso Tosolini

12/29/2007 1:17:00 PM

0

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

:)

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

Tom

Robert Klemme

12/29/2007 5:31:00 PM

0

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?

The simplest and fastest is probably

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

Kind regards

robert