Do I really not understand inheritance?

So, I’ve been really trying to get a firm understanding of objects and
classes in Ruby. Just to make sure I understood what was what, though, I
wrote a program to test my understanding.

As I understand it, asking:

obj.kind_of? mod

…is the same as asking:

obj.class.ancestors.include? mod

So I tested every object-class pair which comes standard with Ruby. It
failed on two of these pairs, both with the Enumerable module. Here’s the
fast version of the code, working only with Enumerable:

def doIGetIt? (obj)
(obj.kind_of?(Enumerable)) == (obj.class.ancestors.include?(Enumerable))
end

ObjectSpace.each_object do |obj1|
if !doIGetIt? obj1
puts obj1.kind_of?(Enumerable)
puts obj1.class.ancestors.inspect
puts obj1
puts obj1.class
puts obj1.inspect
puts
end
end

So, I’m assuming that it fails for you, too. What’s the deal with the ENV
object? And what is that other ‘-’ object?

Chris

Hi –

So, I’ve been really trying to get a firm understanding of objects and
classes in Ruby. Just to make sure I understood what was what, though, I
wrote a program to test my understanding.

As I understand it, asking:

obj.kind_of? mod

…is the same as asking:

obj.class.ancestors.include? mod

Not necessarily. You can extend an object with a module individually:

irb(main):001:0> a = Object.new
#Object:0x401df42c
irb(main):002:0> a.extend(Enumerable)
#Object:0x401df42c
irb(main):003:0> a.kind_of?(Enumerable)
true
irb(main):004:0> a.class.ancestors.include?(Enumerable)
false

Here, I’ve extended the object to include Enumerable, but
only that one object. Extending a means including Enumerable
in a’s singleton class, which isn’t the same as a.class.

And, sure enough:

irb(main):008:0> class << a
irb(main):009:1> puts “Yes” if self.ancestors.include?(Enumerable)
irb(main):010:1> end
Yes

[…]
So, I’m assuming that it fails for you, too. What’s the deal with the ENV
object? And what is that other ‘-’ object?

The object behind ENV does the above: it is an Object object which is
extended with Enumerable. From hash.c:

envtbl = rb_obj_alloc(rb_cObject);
rb_extend_object(envtbl, rb_mEnumerable);

rb_define_global_const(“ENV”, envtbl);

David

···

On Thu, 12 Dec 2002, Chris Pine wrote:


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav