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.dup
TypeError: can't dup Fixnum
	from (irb):1:in `dup'
	from (irb):1

This was confusing because Integer#dup is actually implemented.


> Integer.respond_to? :dup
=> true

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


> 1.freeze
=> 1

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


> 1.dup
=> 1

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.