From fe4b9949f7493cfd9bda9d92534403852a786804 Mon Sep 17 00:00:00 2001 From: Skorobogaty Dmitry Date: Thu, 2 Mar 2023 15:18:54 +0300 Subject: [PATCH] add comparison methods --- lib/ipaddress/ipv4.rb | 17 +++++++++++++++++ lib/ipaddress/ipv6.rb | 20 +++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/lib/ipaddress/ipv4.rb b/lib/ipaddress/ipv4.rb index 82546d6..03bcfd2 100644 --- a/lib/ipaddress/ipv4.rb +++ b/lib/ipaddress/ipv4.rb @@ -515,6 +515,23 @@ def <=>(oth) return prefix <=> oth.prefix if to_u32 == oth.to_u32 to_u32 <=> oth.to_u32 end + + # + # Check if 2 IPs (ranges) are equal + # + # Example: + # + # ip1 = IPAddress '10.0.0.0/24' + # ip2 = IPAddress '10.0.0.0/24' + # ip3 = IPAddress '10.0.0.0/25' + # + # ip1.eql? ip2 # => true + # ip2.eql? ip1 # => true + # ip1.eql? ip3 # => false + def eql?(other) + (!other.is_a? self.class) || (prefix == other.prefix && to_u32 == other.to_u32) + end + alias eql? == # diff --git a/lib/ipaddress/ipv6.rb b/lib/ipaddress/ipv6.rb index 1601a01..ad3fdc6 100644 --- a/lib/ipaddress/ipv6.rb +++ b/lib/ipaddress/ipv6.rb @@ -525,9 +525,27 @@ def each # def <=>(oth) return nil unless oth.is_a?(self.class) - return prefix <=> oth.prefix if to_u128 == oth.to_u128 + return prefix <=> oth.prefix if to_u128 == oth.to_u128 to_u128 <=> oth.to_u128 end + + # Check if 2 IPs (ranges) are equal + # + # Example: + # + # ip1 = IPAddress "2001:db8:1::1/64" + # ip2 = IPAddress "2001:db8:1::1/64" + # ip3 = IPAddress "2001:db8:1::1/65" + # ip4 = IPAddress "2001:db8:2::1/65" + # + # ip1.eql? ip2 # => true + # ip2.eql? ip1 # => true + # ip1.eql? ip3 # => false + # ip4.eql? ip3 # => false + def eql?(other) + (!other.is_a? self.class) || (prefix == other.prefix && to_u128 == oth.to_u128) + end + alias eql? == #