Vra

I'm working with OPE IDs. One file has them with two trailing zeros, eg, [998700, 1001900]. The other file has them with one or two leading zeros for a total length of six, eg, [009987, 010019]. I want to convert every OPE ID (in both files) to an eight-digit string with exactly two leading zeros and however many zeros at the end to get it to be eight digits long.

Was dit nuttig?

Oplossing

Try this:

a = [ "00123123", "077934", "93422", "1231234", "12333" ]
a.map { |n| n.gsub(/^0*/, '00').ljust(8, '0') }

=> ["00123123", "00779340", "00934220", "001231234", "00123330"]

Ander wenke

If you have your data parsed and stored as strings, it could be done like this, for example.

n = ["998700", "1001900", "009987", "0010019"]
puts n.map { |i|
    i =~ /^0*([0-9]+?)0*$/
    "00" + $1 + "0" * [0, 6 - $1.length].max
}

Output:

00998700
00100190
00998700
00100190

This example on codepad.

I'm note very sure though, that I got the description exactly right. Please check the comments and I correct in case it's not exactly what you were looking for.

With the help of the answers given by @detunized & @nimblegorilla, I came up with:

"998700"[0..-3].rjust(6, '0').to_sym

to make the first format I described (always with two trailing zeros) equal to the second.

Gelisensieer onder: CC-BY-SA met toeskrywing
Nie verbonde aan StackOverflow
scroll top