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
相关产品推荐
相关产品推荐

