如果我要列出一個類的所有方法我可以使用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