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

Ruby继承场景下调用instance_methods返回空数组问题求助

问题原因

Ruby类定义是逐行解析执行的:

  • 当代码执行到class Raja < Execute时,Ruby会先创建Raja类,随即触发父类Execute的self.inherited回调。
  • 此时Raja类体内的test_1、test_2、test_3方法还未被定义(类体代码还没执行到),所以调用instance_methods(false)会返回空数组。
解决方案

提供两种可行的修复方式:

方式1:延迟执行run方法

利用at_exit钩子,让run在程序即将退出时执行(此时所有类方法已定义完成):

class Execute
  def self.inherited(klass)
    puts "Class Inherited: #{klass}"
    at_exit { klass.run }
  end

  def self.run
    puts "Running Instance Methods"
    instance_methods(false).each do |m|
      if m.to_s.start_with?("test_")
        puts "Executing Method: #{m}"
        new.send(m)
      end
    end
  end
end

puts "Before class definition"

class Raja < Execute
  def test_1
    puts 'test_1'
  end

  def test_2
    puts 'test_2'
  end

  def test_3
    puts 'test_3'
  end
end

puts "After class definition"

方式2:手动触发run方法

移除inherited中的自动调用,在子类定义完成后手动调用run:

class Execute
  def self.run
    puts "Running Instance Methods"
    instance_methods(false).each do |m|
      if m.to_s.start_with?("test_")
        puts "Executing Method: #{m}"
        new.send(m)
      end
    end
  end
end

puts "Before class definition"

class Raja < Execute
  def test_1
    puts 'test_1'
  end

  def test_2
    puts 'test_2'
  end

  def test_3
    puts 'test_3'
  end
end

puts "After class definition"
Raja.run # 手动执行测试方法
运行结果

两种方式执行后都会输出:

Before class definition
Class Inherited: Raja
After class definition
Running Instance Methods
Executing Method: test_1
test_1
Executing Method: test_2
test_2
Executing Method: test_3
test_3

内容的提问来源于stack exchange,提问作者Rajagopalan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:41:12