[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Arrgh when 'class << object'ing...

Asfand Yar Qazi

12/1/2003 3:20:00 PM

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-...

2 Answers

Mark J. Reed

12/1/2003 3:22:00 PM

0

On Mon, Dec 01, 2003 at 03:20:16PM +0000, Asfand Yar Qazi wrote:
> Where's the "Attr"?!!!!!!

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

ts

12/1/2003 3:29:00 PM

0

>>>>> "A" == Asfand Yar Qazi <im_not_giving_it_here@i_hate_spam.com> writes:

A> def test()
A> self.class.included_modules.each() {|i| puts(i)}
A> 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