On Sat, Dec 13, 2008 at 6:25 AM, Daniel DeLorme <dan-ml / dan42.com> wrote:
> If I understand the ruby object model correctly, then an object's singleton
> methods are defined as the instance methods of that object's meta/singleton
> class. So I tried to confirm this:
>
> obj = Object.new
> obj_meta = (class << obj;self;end)
> def obj.foobar; end
> obj.singleton_methods            #=> ["foobar"]
> obj_meta.instance_methods(false) #=> ["foobar"]
>
> So far so good. But if I try the same thing with a class:
>
> class A; end
> A_meta = (class << A;self;end)
> def A.foobar; end
> A.singleton_methods            #=> ["foobar"]
> A_meta.instance_methods(false) #=> ["allocate", "superclass", "foobar",
> "new"]
>
> I understand why those 3 extra methods appear, but in that case shouldn't
> they also appear as part of A.singleton_methods? Furthermore this does not
> happen with builtin classes. Does anyone have an explanation for what is
> going on here?
>
> Daniel
>
Daniel first, I had some difficulties to see what puzzles you. The
fact that meta methods are not singleton methods made perfectly sense,
but than I tried to define meta methods, which you did not, and then I
was as puzzled as you were ;)
----------------------------------------------- 8< ------------------------
507/15 > cat test1.rb && ruby test1.rb
#!/usr/bin/ruby
# vim: sw=2 ts=2 ft=ruby expandtab tw=0 nu syn=on:
# file: test1.rb

def all_methods an_obj
  p(
    { :name => an_obj.name,
      :meta => class << an_obj; instance_methods( false ).sort end,
      :single => an_obj.singleton_methods( false ).sort }
  )
end


def Object.answer; 42 end
def (A=Class::new).answer; 42 end
all_methods Object
all_methods A

class << Object; def almost; 41 end end
class << A; def almost; 41 end end
all_methods Object
all_methods A
{:meta=>["allocate", "answer", "new", "superclass"],
:single=>["answer"], :name=>"Object"}
{:meta=>["allocate", "answer", "new", "superclass"],
:single=>["answer"], :name=>"A"}
{:meta=>["allocate", "almost", "answer", "new", "superclass"],
:single=>["almost", "answer"], :name=>"Object"}
{:meta=>["allocate", "almost", "answer", "new", "superclass"],
:single=>["almost", "answer"], :name=>"A"}
------------------------------------------------ >8
---------------------------------------------------

So you are right it does not seem possible to create that kind of
diversity ourselves.
I could however not see the difference between A and Object, can you
explain please?

Cheers
Robert

>



-- 
Il computer non una macchina intelligente che aiuta le persone
stupide, anzi, una macchina stupida che funziona solo nelle mani
delle persone intelligenti.
Computers are not smart to help stupid people, rather they are stupid
and will work only if taken care of by smart people.

Umberto Eco