You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何列出类的专属实例方法(排除父类)及Object类独有实例方法

Hey there! Let's work through these two Ruby method-listing tasks clearly:

1. List a class's instance methods (exclude parent class methods, include module methods)

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.

2. List only instance methods defined directly in Object (exclude modules/other classes)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:35:45