Ruby gsub is repeating on ip address

Viewed 39

My program is suppose to keep track of every ip address and map them to a random one, then proceed to gsub all the ip's with the randoms. My gsub however is working on places that don't quite have the ip address in there (it appends to the back of a url with a bunch of numbers where it appends the ip address in front of the numbers) or when it does replace an ip address, it replaces it multiple times over.

v is a random string like "https://10.110.0.100/html/1202234"

That when this runs, turns into

https://227.95.94.95227.95.94.95227.95.94.95227.95.94.95227.95.94.95227.95.94.95227.95.94.95227.95.94.95227.95.94.95227.95.94.95227.95.94.95227.95.94.95227.95.94.95/html/227.95.94.952227.95.94.952234
ipsRand = Hash[]
ips = v.scan(/(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)/)
ips.each { |x|
if ips.length > 0
    ips.each { |x|
        if !ipsRand.key?(x)
            ip = "%d.%d.%d.%d" % [rand(256), rand(256), rand(256), rand(256)]
            ipsRand["#{x}"] = ip
            v.gsub!(/#{x}/, ip) 
        else
            v.gsub!(/#{x}/, ipsRand["#{x}"])
        end 
    }
end

Not exactly sure what to do here, when I swap /#{x} with the regex used to scan out the ip address, the gsub works just fine but then I can't map out each ip address to the correct random one.

1 Answers

It's much easier if you use a hash with a default value:

ips_rand = Hash.new do |h, k|
  h[k] = '%d.%d.%d.%d' % [rand(256), rand(256), rand(256), rand(256)]
end

That hash will create a new, random IP everytime it is called (with an unknown IP) and re-use it afterwards (when called with a known IP).

Furthermore, it can directly be passed to gsub:

PATTERN = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/

a = 'https://10.110.0.100/foo/bar'
b = 'https://10.110.0.100/baz/qux'
c = 'https://20.220.0.200/quux'

a.gsub(PATTERN, ips_rand) #=> "https://213.19.202.167/foo/bar"
b.gsub(PATTERN, ips_rand) #=> "https://213.19.202.167/baz/qux"
c.gsub(PATTERN, ips_rand) #=> "https://26.21.120.130/quux"
ips_rand
#=> {"10.110.0.100"=>"213.19.202.167", "20.220.0.200"=>"26.21.120.130"}
Related