1

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.

3
  • Do you want all of them to have 2 leading zeroes or just ones that already have them?
    – detunized
    Dec 6, 2010 at 19:41
  • 2
    Best would be if you showed what result you'd like to get.
    – detunized
    Dec 6, 2010 at 19:51
  • @detunized, all of them. Thank you. I edited my question to make it more clear.
    – ma11hew28
    Feb 14, 2019 at 23:41

3 Answers 3

3

Try this:

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

=> ["00123123", "00779340", "00934220", "001231234", "00123330"]
1
  • I like the ljust usage here
    – ma11hew28
    Dec 6, 2010 at 20:31
1

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.

1

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.

1
  • you have a typo, get rid of . after your number string Feb 14, 2019 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.