Avoid exception for dup on Integer

Rohit Arolkar

Rohit Arolkar

August 1, 2017

This blog is part of our  Ruby 2.4 series.

Prior to Ruby 2.4, if we were to dup an Integer, it would fail with a TypeError.

1
2> 1.dup
3TypeError: can't dup Fixnum
4	from (irb):1:in `dup'
5	from (irb):1
6

This was confusing because Integer#dup is actually implemented.

1
2> Integer.respond_to? :dup
3=> true
4

However, if we were to freeze an Integer it would fail silently.

1
2> 1.freeze
3=> 1
4

Ruby 2.4 has now included dup-ability for Integer as well.

1
2> 1.dup
3=> 1
4

In Ruby, some object types are immediate variables and therefore cannot be duped/cloned. Yet, there was no graceful way of averting the error thrown by the sanity check when we attempt to dup/clone them.

So now Integer#dup functions exactly the way freeze does -- fail silently and return the object itself. It makes sense because nothing about these objects can be changed in the first place.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.