Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The answer to "<a href="https://stackoverflow.com/questions/3303347/given-a-class-see-if-instance-has-method-ruby/3304680#3304680">Given a class, see if instance has method (Ruby)</a>" is better. Apparently Ruby has this built-in, and I somehow missed it. My answer is left for reference, regardless.</p> <p>Ruby classes respond to the methods <a href="http://ruby-doc.org/core/Module.html#method-i-instance_methods" rel="nofollow noreferrer"><code>instance_methods</code></a> and <a href="http://ruby-doc.org/core/Module.html#method-i-public_instance_methods" rel="nofollow noreferrer"><code>public_instance_methods</code></a>. In Ruby 1.8, the first lists all instance method names in an array of strings, and the second restricts it to public methods. The second behavior is what you'd most likely want, since <code>respond_to?</code> restricts itself to public methods by default, as well.</p> <pre><code>Foo.public_instance_methods.include?('bar') </code></pre> <p>In Ruby 1.9, though, those methods return arrays of symbols.</p> <pre><code>Foo.public_instance_methods.include?(:bar) </code></pre> <p>If you're planning on doing this often, you might want to extend <code>Module</code> to include a shortcut method. (It may seem odd to assign this to <code>Module</code> instead of <code>Class</code>, but since that's where the <code>instance_methods</code> methods live, it's best to keep in line with that pattern.)</p> <pre><code>class Module def instance_respond_to?(method_name) public_instance_methods.include?(method_name) end end </code></pre> <p>If you want to support both Ruby 1.8 and Ruby 1.9, that would be a convenient place to add the logic to search for both strings and symbols, as well.</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. 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