attr_accessor/_reader/_writer and method_defined?

Discussion in 'Ruby' started by David Garamond, Jan 25, 2004.

  1. Why does a method defined using attr_accessor/_reader/_writer is not
    found by .method_defined? For example:

    $ irb
    irb(main):001:0> require 'pp'
    => true
    irb(main):002:0> PP.method_defined? :pp
    => true
    irb(main):003:0> PP.method_defined? :sharing_detection
    => false
    irb(main):004:0> PP.respond_to? :sharing_detection
    => true

    --
    dave
     
    David Garamond, Jan 25, 2004
    #1
    1. Advertising

  2. David Garamond

    Dan Doel Guest

    My guess:

    Taking a peek at pp.rb, #pp is defined for several things, including Kernel.
    Kernel methods get included in everything, which means everything gets an
    instance method #pp.

    I'm guessing that #method_defined? tells you if objects of the given Module
    have a given instance method. #sharing_detection is an accessor for the
    class instance variable @sharing_detection of PP, defined as:

    class << PP
    attr_accessor :sharing_detection
    end

    Or some such. This means that the class in which the method is defined is
    the singleton class of PP, accessed by:

    class << PP; self; end

    Sure enough, if you call method_defined? on the singleton class, you get
    true.

    So:

    PP responds to #sharing_detection, but it's defined in its singleton class.
    PP defines a method #pp, so objects of class PP will respond to #pp.
    Kernel defines a method #pp so objects including Kernel will respond to #pp.

    Hope this clears things up.

    - Dan
     
    Dan Doel, Jan 25, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    7
    Views:
    96
    Dumaiu
    Jul 24, 2006
  2. Tim Becker
    Replies:
    5
    Views:
    122
    Daniel Berger
    Nov 29, 2006
  3. matt neuburg
    Replies:
    2
    Views:
    78
    matt neuburg
    Jan 27, 2008
  4. Iñaki Baz Castillo

    Where and how is defined "attr_accessor"?

    Iñaki Baz Castillo, Apr 30, 2008, in forum: Ruby
    Replies:
    2
    Views:
    110
    Ken Bloom
    May 1, 2008
  5. Intransition

    method_defined? does what exactly?

    Intransition, Jun 4, 2010, in forum: Ruby
    Replies:
    7
    Views:
    270
    Intransition
    Jun 5, 2010
Loading...

Share This Page