获取类的实例方法的列表 [英] Get list of a class' instance methods

查看:168
本文介绍了获取类的实例方法的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

如何获取此类中的方法列表(method1method2method3)?

How can I get a list of my methods in this class (method1, method2, method3)?

推荐答案

您实际上想要TestClass.instance_methods,除非您对TestClass本身的功能感兴趣.

You actually want TestClass.instance_methods, unless you're interested in what TestClass itself can do.

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

TestClass.methods.grep(/method1/) # => []
TestClass.instance_methods.grep(/method1/) # => ["method1"]
TestClass.methods.grep(/new/) # => ["new"]

或者您可以在对象上调用methods(不是instance_methods):

Or you can call methods (not instance_methods) on the object:

test_object = TestClass.new
test_object.methods.grep(/method1/) # => ["method1"]

这篇关于获取类的实例方法的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆