Advertisement
Guest User

Untitled

a guest
Aug 27th, 2014
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.26 KB | None | 0 0
  1. class IP
  2.     # Class method containsIP first checks for a valid IP address in the string
  3.     # and then creates an instance of IP
  4.     def self.containsIP?(ipaddress)
  5.         if (ipaddress.is_a?(String))
  6.             # Search the string for regular IP address pattern and convert result into
  7.             # an array
  8.             m = ipaddress.match(/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/).to_a
  9.  
  10.             # Delete the ipaddress from the resulting array
  11.             m.delete(ipaddress)
  12.  
  13.             # Convert the string literals into integers
  14.             i = Array.new
  15.             m.each { |s| i << s.to_i }
  16.             if (i.size == 4)
  17.                 # a, b, d and d all in valid range?
  18.                 if (i - (0..255).to_a).empty?
  19.                     new(i[0], i[1], i[2], i[3])
  20.                 else
  21.                     puts "IP is not in valid range."
  22.                 end
  23.             else
  24.                 puts "Did not find a valid IP address in #{ipaddress}"
  25.             end
  26.         else
  27.             puts "Error: I expected a string containing an IP address."
  28.         end
  29.     end
  30.  
  31.     def initialize(a, b, c, d)
  32.         @a = a
  33.         @b = b
  34.         @c = c
  35.         @d = d
  36.     end
  37.  
  38.     def to_s
  39.         "#{@a}.#{@b}.#{@c}.#{@d}"
  40.     end
  41. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement