如何列出类的专属实例方法(排除父类)及Object类独有实例方法
Hey there! Let's work through these two Ruby method-listing tasks clearly:
When you need to grab all instance methods tied to a specific class—including any from modules it includes, but leaving out anything inherited from its parent class—the trick is to subtract the parent's method list from the current class's full method set.
Let's use a concrete example to show how this works:
# A module with reusable methods module Notifiable def send_alert; end def mark_as_read; end end # Parent class with its own instance method class Item def display; end end # Child class that inherits from Item and includes Notifiable class Order < Item include Notifiable def process_payment; end end
To get only the methods specific to Order (including Notifiable's methods, excluding Item's):
order_specific_methods = Order.instance_methods - Item.instance_methods puts order_specific_methods.inspect # Output: [:process_payment, :send_alert, :mark_as_read]
Here's why this works: Order.instance_methods returns every instance method available to Order instances (inherited, module-included, and self-defined). Subtracting Item.instance_methods strips out the methods inherited from the parent, leaving exactly the methods that belong to Order itself plus those from included modules.
If you want strictly the instance methods that are defined directly in the Object class—not inherited from BasicObject, not pulled in from modules like Kernel—use Object.instance_methods(false). The false argument tells Ruby to only return methods that originate in the class itself, ignoring inherited or module-provided methods.
Example code:
object_own_methods = Object.instance_methods(false) puts object_own_methods.inspect # Sample output (varies by Ruby version): # [:__id__, :__send__, :object_id, :instance_eval, :instance_exec, :__binding__]
For comparison, if you omit the false argument, you'll get all methods available to Object instances, including those from Kernel (like puts, p, etc.):
all_object_methods = Object.instance_methods puts all_object_methods.include?(:puts) # => true puts object_own_methods.include?(:puts) # => false
内容的提问来源于stack exchange,提问作者Miguel Salas

