And*_*rew 35 ruby introspection public-method
给定任何对象我可以调用#public_methods并查看它将响应的所有方法.但是,我发现有时候获得一个没有继承的所有公共方法的快速列表是有用的,也就是那些真正属于这个类的东西.
我找到了" 简单的方法列出Ruby对象的公共方法 ",如果我使用:
(Foo.public_methods - Object.public_methods).sort
Run Code Online (Sandbox Code Playgroud)
我可以过滤掉很多基本的Ruby东西.我希望能够过滤掉链条上一直延续的所有内容.如果我知道父类我可以使用它进行过滤,但我想提出一个通用命令,它可以返回任何对象的未公开公共方法的数组.
Mar*_*une 59
只是通过false以下inherited论点public_methods:
"hello".public_methods.include?(:dup) # => true
"hello".public_methods(false).include?(:dup) # => false
Run Code Online (Sandbox Code Playgroud)
不是你的问题的答案,但如果你不知道,irb自动完成,所以很容易得到公共方法的列表(特别是如果你知道你正在寻找的方法的开头).只需点击标签; 两次击中将列出所有可能性(包括继承的可能性):
> "nice".d<tab><tab>
"nice".delete "nice".delete! "nice".display "nice".downcase
"nice".downcase! "nice".dump "nice".dup "nice".define_singleton_method
> "nice".<tab><tab>
Display all 162 possibilities? (y or n)
...
Run Code Online (Sandbox Code Playgroud)
使用pry可以更容易地看到可用的方法,按继承级别细分:
[1] pry(main)> cd "nice"
[2] pry("nice"):1> ls
Comparable#methods: < <= > >= between?
String#methods: % * + << <=> == === =~ [] []= ascii_only? bytes bytesize byteslice capitalize capitalize! casecmp center chars chomp chomp! chop chop! chr clear codepoints concat count crypt delete delete! downcase downcase! dump each_byte each_char each_codepoint each_line empty? encode encode! encoding end_with? eql? force_encoding getbyte gsub gsub! hash hex include? index insert inspect intern length lines ljust lstrip lstrip! match next next! oct ord partition prepend replace reverse reverse! rindex rjust rpartition rstrip rstrip! scan setbyte shellescape shellsplit size slice slice! split squeeze squeeze! start_with? strip strip! sub sub! succ succ! sum swapcase swapcase! to_c to_f to_i to_r to_s to_str to_sym tr tr! tr_s tr_s! unpack upcase upcase! upto valid_encoding?
locals: _ _dir_ _ex_ _file_ _in_ _out_ _pry_
Run Code Online (Sandbox Code Playgroud)
Mar*_*hen 10
看看Module#instance_methods.该方法有一个布尔参数,include_super是否也返回继承的方法.默认值为true.
您可以使用以下内容:
class A
def method_1
puts "method from A"
end
end
class B < A
def method_2
puts "method from B"
end
end
B.instance_methods # => [:method_1, :method_2, ...]
B.instance_methods(false) # => [:method_2]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12114 次 |
| 最近记录: |