Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all, the way to list singleton methods is with <code>singleton_methods</code>. The <code>methods</code> method returns a list of the names of public and protected methods of the object. Also, it is defined in the <a href="http://ruby-doc.org/core-2.3.0/Object.html#method-i-methods" rel="nofollow noreferrer"><code>Object</code></a> class. Try <code>extend</code>ing an instance. It is one of the most elegant ways, as it supports code reuse and seems to me very object-oriented:</p> <pre><code>class Foo def bar puts "Hi" end end module Bar def foo puts "Bye" end end f = Foo.new f.bar #=&gt; hi f.extend Bar f.foo #=&gt; bye f.methods(false) #=&gt; [] # the module we extended from is not a superclass # therefore, this must be empty, as expected f.singleton_methods #=&gt; ["foo"] # this lists the singleton method correctly g = Foo.new g.foo #=&gt; NoMethodError </code></pre> <p><strong>Edit</strong>: In the comment you asked why <code>methods(false)</code> returns nothing in this case. After reading through the C code it seems that:</p> <ul> <li><code>methods</code> returns all the methods available for the object (also the ones in included modules)</li> <li><code>singleton_methods</code> returns all the singleton methods for the object (also the ones in included modules) (<a href="http://ruby-doc.org/core/classes/Object.html#M001026" rel="nofollow noreferrer">documentation</a>)</li> <li><code>singleton_methods(false)</code> returns all the singleton methods for the object, but <strong>not</strong> those declared in included modules</li> <li><code>methods(false)</code> supposedly returns the singleton methods by calling <code>singleton_methods</code>, <strong>but</strong> it also passes the parameter <code>false</code> to it; whether this is a bug or a feature - I do not know</li> </ul> <p>Hopefully, this clarifies the issue a little. Bottom line: call <code>singleton_methods</code>, seems more reliable.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload