Is an instance of a class really an instance of its superclass too?

I understand that the answer to that question is yes.

But then a singleton class (using require ‘singleton’) can have two or
more instances in a Ruby program, like:

require ‘singleton’

class Super
include Singleton
end
class Sub < Super
end

puts Super.instance
puts Sub.instance

#=> Super:0x000000024b5648
#=> Sub:0x000000024b55d0

Doesn’t this mean we have two instances of a class (Super) whose only
one instance should have been in the program (because the class included
‘singleton’)? IOW, shouldn’t class Sub < Super be disallowed?

Thanks,
Kedar

On Jan 24, 2011, at 8:41 PM, Kedar M. wrote:

Doesn’t this mean we have two instances of a class (Super) whose only
one instance should have been in the program (because the class included
‘singleton’)? IOW, shouldn’t class Sub < Super be disallowed?

I think you answer your own question. The contract created by the
‘singleton’ feature is in regards to direct instances and not indirect
instances via a subclass.

Making the contract more restrictive as you suggest, would limit the use
cases for no particular reason. If you don’t want a subclass, then don’t
create one. In general I think it is better to avoid arbitrary
restrictions. In most cases, with Ruby, those restrictions don’t really
prevent anything because methods and classes can always be redefined.

Gary W.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs