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.

# Ruby 2.3

>> IPAddr.new("1.2.1.3") == "Some ip address"
=> IPAddr::InvalidAddressError: invalid address

But if the first argument is invalid IP address and second is valid IP address, then it would return false.

# Ruby 2.3

>> "Some ip address" == IPAddr.new("1.2.1.3")
=> false

The <=> method would raise exception in both the cases.

# Ruby 2.3

>> "Some ip address" <=> IPAddr.new("1.2.1.3")
=> IPAddr::InvalidAddressError: invalid address

>> IPAddr.new("1.2.1.3") <=> "Some ip address"
=> IPAddr::InvalidAddressError: invalid address

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.

# Ruby 2.4

>> IPAddr.new("1.2.1.3") == "Some ip address"
=> false

>> "Some ip address" == IPAddr.new("1.2.1.3")
=> false

>> IPAddr.new("1.2.1.3") <=> "Some ip address"
=> nil

>> "Some ip address" <=> IPAddr.new("1.2.1.3")
=> nil

This might cause some backward compatibility if our code is expecting the exception which is no longer raised in Ruby 2.4.