Arrgh when 'class << object'ing

Me again, sorry about this.

#!/usr/bin/ruby -w

module Attr; end

class << (j = Object.new())

 include Attr

 def test()
self.class.included_modules.each() {|i| puts(i)}
 end

end

j.test()

···

Output:

Kernel

Where’s the “Attr”!!!


http://www.it-is-truth.org/

It’s not there because the self.class call skips right over the
singleton class and returns the proper, named, original class:

irb(main):001:0> s="Hello"
=> "Hello"
irb(main):002:0> s.class
=> String
irb(main):003:0> class << s
irb(main):004:1> def greet(greetee="World")
irb(main):005:2> puts "#{self}, #{greetee}!"
irb(main):006:2> end
irb(main):007:1> end
=> nil
irb(main):008:0> s.class
=> String

And the original class doesn’t have Attr included.

AFAIK there’s no built-in method to get the singleton class of an object,
but someone just posted a pointer to code that does it over in the
“class << x” thread.

-Mark

···

On Mon, Dec 01, 2003 at 03:20:16PM +0000, Asfand Yar Qazi wrote:

Where’s the “Attr”!!!

     def test()
  self.class.included_modules.each() {|i| puts(i)}
     end

svg% cat b.rb
#!/usr/bin/ruby
module Attr end

class << (j = Object.new())

     include Attr

     def test
        p class << self; self end.included_modules
     end
end

j.test()

svg%

svg% b.rb
[Attr, Kernel]
svg%

"self.class" will give you Object (the class of `j')

"class << self; self end" will give you the singleton class associated
with `j'. The "include Attr" was made in this singleton class

Guy Decoux

Many thanks.

···


http://www.it-is-truth.org/