Ruby pad IP address with zeros

Not sure why this was so difficult to figure out, but the Googs failed me when I tried to look this up. So here it is for my fellow lazy sysadmins who want IP fields to line up nice and pretty.


##
# For pretty printing, align text with equal char length of IPs

def pad_ip_with_zeros(ipString)
  arr = ipString.to_s.split('.')
  barr = []
  arr.each {|octet|
    barr.push(octet.rjust(3,'0'))
  }

  return barr.join('.')
end #def pad_ip_with_zeros(ipString)

##
# Undo pretty printing of IP address

def unpad_ip_with_zeros(ipString)
  arr = ipString.to_s.split('.')
  barr = []
  arr.each {|octet|
    barr.push(octet.to_i)
  }

  return barr.join('.')
end #def pad_ip_with_zeros(ipString)

Tags:

Leave a Reply

XHTML: You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>