This blog is part of our Ruby 2.4 series.
In Ruby, IPAddr#== method is used to check whether two IP addresses are equal or not. Ruby also has IPAddr#<=> method which is used to compare two IP addresses.
In Ruby 2.3, behavior of these methods was inconsistent. Let's see an example.
1 2# Ruby 2.3 3 4>> IPAddr.new("1.2.1.3") == "Some ip address" 5=> IPAddr::InvalidAddressError: invalid address
But if the first argument is invalid IP address and second is valid IP address, then it would return false.
1 2# Ruby 2.3 3 4>> "Some ip address" == IPAddr.new("1.2.1.3") 5=> false 6
The <=> method would raise exception in both the cases.
1 2# Ruby 2.3 3 4>> "Some ip address" <=> IPAddr.new("1.2.1.3") 5=> IPAddr::InvalidAddressError: invalid address 6 7>> IPAddr.new("1.2.1.3") <=> "Some ip address" 8=> IPAddr::InvalidAddressError: invalid address 9
In Ruby 2.4, this issue is fixed for both the methods to return the result without raising exception, if the objects being compared can't be converted to an IPAddr object.
1 2# Ruby 2.4 3 4>> IPAddr.new("1.2.1.3") == "Some ip address" 5=> false 6 7>> "Some ip address" == IPAddr.new("1.2.1.3") 8=> false 9 10>> IPAddr.new("1.2.1.3") <=> "Some ip address" 11=> nil 12 13>> "Some ip address" <=> IPAddr.new("1.2.1.3") 14=> nil
This might cause some backward compatibility if our code is expecting the exception which is no longer raised in Ruby 2.4.