简体   繁体   中英

How to list all methods of Array in Ruby programmatically?

I want to list all methods of Array in Ruby. How do I approach that?

Class methods like Array.try_convert can be listed via Objects#methods

Array.methods
#=> [:try_convert, :[], :allocate, :superclass, :new, :<=>, :<=, :>=, :==, ...]

It returns many additional methods because ( Array being in instance of Class ) it also includes the instance methods from Class . To get only the Array specific class methods, we can pass false :

Array.methods(false)
#=> [:try_convert, :[]]

Instance methods like Array#at can be listed via Module#instance_methods :

Array.instance_methods
#=> [:to_h, :include?, :at, :fetch, :last, ..., :instance_eval, :__id__, :__send__]

Again, we can pass false to exclude the inherited methods:

Array.instance_methods(false)
#=> [:to_h, :include?, :at, :fetch, :last, ..., :slice, :slice!, :dig, :hash]
 p Array.instance_methods(false)

这将列出数组的所有实例方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM