---
title: "Ruby 2.4 no exception for objects converted to IPAddr"
description:
  "IPAddr#== and IPAddr# do not throw exception for objects that can't be
  converted to IPAddr anymore in Ruby 2.4"
canonical_url: "https://www.bigbinary.com/blog/ruby-2-4-ip-addr-methods-do-not-throw-exception-for-objects-that-cant-be-converted-to-ipaddr"
markdown_url: "https://www.bigbinary.com/blog/ruby-2-4-ip-addr-methods-do-not-throw-exception-for-objects-that-cant-be-converted-to-ipaddr.md"
---

# Ruby 2.4 no exception for objects converted to IPAddr

IPAddr#== and IPAddr# do not throw exception for objects that can't be converted
to IPAddr anymore in Ruby 2.4

- Author: Sushant Mittal
- Published: June 21, 2017
- Categories: Ruby 2.4, Ruby

In Ruby,
[`IPAddr#==`](https://docs.ruby-lang.org/en/2.4.0/IPAddr.html#method-i-3D-3D)
method is used to check whether two IP addresses are equal or not. Ruby also has
[`IPAddr#<=>`](https://docs.ruby-lang.org/en/2.4.0/IPAddr.html#method-i-3C-3D-3E)
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

# 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

# Ruby 2.3

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

```

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

```ruby

# 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](https://bugs.ruby-lang.org/issues/12799) is
[fixed](https://github.com/ruby/ruby/pull/1435/files#diff-3504e08cf251c76a597c727011315dd1)
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

# 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.

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-2-4-ip-addr-methods-do-not-throw-exception-for-objects-that-cant-be-converted-to-ipaddr)
