Search code examples
ruby-on-railsregexgsubipv4

Rails: Convert last n quartet's of IPv4 address to wildcard


I would like to be able to do

irb(main):054:0> ip = "192.168.1.255"
=> "192.168.1.255"
irb(main):055:0> ip.sub(/\d+$/, '*')
=> "192.168.1.*"

for the last n quartets. e.g. "192.168.1.255" => "192.168.*.*" etc.


Solution

  • You can split the ip on "." and get an array of quartets.

    def wildcard_ip(ip, n)
      len = ip.split('.').size
      ip.split('.').each_with_index.map{|q,i| i < len-n ? q : '*'}.join('.')
    end