如果我要列出一个类的所有方法我可以使用Class_Name.methods
,因此,例如,可列出FixNum
类的所有方法:在Ruby中打印一个类的所有方法名称?
> 5.methods
=> [:to_s, :[email protected], :+, :-, :*, :/, :div, :%, :modulo, :divmod, :fdiv, :**, :abs, :magnitude, :==, :===, :<=>, :>, :>=, :<, :<=, :~, :&, :|, :^, :[], :<<, :>>, :to_f, :size, :zero?, :odd?, :even?, :succ, :integer?, :upto, :downto, :times, :next, :pred, :chr, :ord, :to_i, :to_int, :floor, :ceil, :truncate, :round, :gcd, :lcm, :gcdlcm, :numerator, :denominator, :to_r, :rationalize, :singleton_method_added, :coerce, :i, :[email protected], :eql?, :quo, :remainder, :real?, :nonzero?, :step, :to_c, :real, :imaginary, :imag, :abs2, :arg, :angle, :phase, :rectangular, :rect, :polar, :conjugate, :conj, :between?, :nil?, :=~, :!~, :hash, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
这份名单是真的很难看。我也尝试过5.methods.sort
,但这并没有让它更具可读性。
我经常在日常编程中使用方法列表。有没有一种方法可以很好地打印这个文件,所以它变得更容易阅读?
我对Ruby有点新,但PrettyPrint类可能有所帮助 – 2012-04-23 15:19:37
您可能有兴趣找到特定的方法,而不是查看所有方法:https://github.com/citizen428/methodfinder(声明:这个宝石的作者)。 – 2012-04-23 15:33:57
很高兴在一个地方有这些很酷,有用的答案。感谢问! – vlasits 2012-04-23 15:36:50