rubystringprintfzero-pad

Ruby String pad zero OPE ID


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.


Solution

  • Try this:

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