我有一门课:

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

我怎样才能得到这个类中的方法列表(method1method2method3)?

推荐答案

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

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):

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

Ruby相关问答推荐

Ruby 扁平化 JSON 对象或哈希

多线程期间的 MRI ruby​​ 内存访问特性

Ruby中带和不带下划线_的方法参数有什么区别

Rspec: expectvsexpect什么区别?

判断Ruby中的目录是否为空

无法在 Heroku 教程中使用 Python 启动工头

Ruby 对象打印为指针

rbenv 没有显示可用的 ruby​​ 版本

卸载所有 gem Ruby 2.0.0

你能用 Ruby 开发原生 iPhone 应用程序吗?

动态设置 Ruby 对象的属性

git,Heroku:预接收挂钩被拒绝

include_examples和it_behaves_like有什么区别?

RSpec allow/expec vs expect/and_return

如何在 Mac OS X Lion 中安装 Ruby 1.9.3?

Sublime Text 2 控制台输入

是什么让 Ruby 变慢了?

使用 Ruby CSV 在导出的 CSV 中更改字段分隔符/分隔符

工厂女孩 - 目的是什么?

判断文件名是文件夹还是文件