Class.new and inspect

H

Hal Fulton

I'm curious as to how this little bit of magic works:

hal@alpha ~/projects/peco $ irb
irb(main):001:0> foo = Class.new(Array)
=> #<Class:0x40202470>
irb(main):002:0> MyArray = Class.new(Array)
=> MyArray
irb(main):003:0>

In other words, when I create a class with Class.new, *and* assign it
to a constant, somehow it knows its own name (via inspect), just as
if I had done "class MyArray < Array".

In the latter case, somehow it's more understandable to me.


Perhaps even more perplexing:

irb(main):007:0> A = B = C = Class.new(Hash)
=> B
irb(main):008:0> x = C.new
=> {}
irb(main):009:0> x.class
=> B

What? Not A or C, the first or last, but B?


Anyone?


Hal
 
Y

Yukihiro Matsumoto

Hi,

In message "Class.new and inspect"

|Perhaps even more perplexing:
|
| irb(main):007:0> A = B = C = Class.new(Hash)
| => B
| irb(main):008:0> x = C.new
| => {}
| irb(main):009:0> x.class
| => B
|
|What? Not A or C, the first or last, but B?

When inspecting unnamed class, Ruby look around the constants for the
name of the class, B this case is found first.

matz.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top