How do I know if an object can be duplicated?

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

+4
source share
2 answers

, , ( - , ).

, , BasicObject Object .

, , , .duplicable? ​​ .

bugs.ruby-lang.org/projects/ruby-trunk

+1

obj, ( Ruby 2 ), , obj.frozen? true , obj , true , obj ; :.

1.frozen?     #=> true
:a.frozen?    #=> true
'cat'.frozen? #=> false

, obj ( obj ), , , obj.class.respond_to? :new true:

1.class.respond_to? :new     #=> false
:a.class.respond_to? :new    #=> false
'cat'.class.respond_to? :new #=> true

"" (, ).

+1

All Articles