开发者

Ruby String pad zero OPE ID

开发者 https://www.devze.com 2023-01-28 22:45 出处:网络
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 wa

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.


Try this:

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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消