I am implementing a method to_afor a class, and I want all the objects that can be duplicated (e.g. String) to be duplicated, leaving only other types (e.g., Symboland Integer)). At first I thought it was simple:
if object.respond_to? :dup
object.dup
else
object
end
It turns off, all objects react to :dup, but integers and characters cause a type error. I could do this:
begin
object.dup
rescue TypeError
object
end
But I want to avoid using exceptions for control flow.
Is there a way to check if an object can be duplicated without relying on exceptions?
I am using Ruby 2.0.0
source
share