0

我正在查看对象的所有方法。我怎样才能避免所有的零?

r=1..10
r.methods.map{|m| puts m}
===
eql?
hash
each
step
bsearch
begin
end
first
...
instance_exec
__send__
__id__
 => [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
...
nil, nil, nil, nil, nil, nil, nil, nil, nil] 
2.0.0-p247 :004 > 
4

2 回答 2

3

您所做的map是在另一个数组中返回结果.. 并puts返回nil.. 并irb 打印返回值。所以这是预期的行为

puts r.methods您可以使用或irb仅打印出方法r.methods

irb(main):002:0> (1..2).methods
=> [:==, :===, :eql?, :hash, :each, :step, :begin, :end, :first, :last, :min, :max, :to_s, :inspect, :exclude_end?, :member?, :include?, :cover?, :to_a, :entries, :sort, :sort_by, :grep, :count, :find, :detect, :find_index, :find_all, :select, :reject, :collect, :map, :flat_map, :collect_concat, :inject, :reduce, :partition, :group_by, :all?, :any?, :one?, :none?, :minmax, :min_by, :max_by, :minmax_by, :each_with_index, :reverse_each, :each_entry, :each_slice, :each_cons, :each_with_object, :zip, :take, :take_while, :drop, :drop_while, :cycle, :chunk, :slice_before, :nil?, :=~, :!~, :<=>, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :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__]

如果你想让它们各自在自己的线上,你也.join "\n"可以

另外,为了清楚起见,该数组是表达式的返回值,默认显示在irb. 如果您像在文件中那样编写代码,它将被忽略。在这种情况下不会打印。

于 2013-08-17T13:53:44.093 回答
2

利用Array#each

(1..10).methods.each {|m| puts m}
于 2013-08-17T14:09:54.397 回答