【发布时间】:2012-04-23 15:14:12
【问题描述】:
如果我想列出一个类的所有方法,我可以使用Class_Name.methods,例如,列出FixNum 类中的所有方法:
> 5.methods
=> [:to_s, :-@, :+, :-, :*, :/, :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, :+@, :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 类可能会有所帮助
-
您可能有兴趣查找特定方法,而不是查看所有方法:github.com/citizen428/methodfinder(免责声明:我是此 gem 的作者)。
-
很高兴在一个地方提供所有这些很酷、有用的答案。感谢您的提问!
-
@MichaelKohl 这在我们知道该做什么但不知道该方法能做什么的时候应该很方便。真的很有趣的想法!
-
也许标题不清楚,但问题是如何以可读的形式打印列表。这是一个不同的问题。
标签: ruby