2013-08-17 43 views
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 > 

回答

3

map做的是在另一個數組..和puts回報nil返回結果..和irb打印返回值。所以這是預期的行爲

可以打印出來的方法與puts r.methodsirb只是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中。如果您像在文件中一樣編寫代碼,它將被忽略。在這種情況下不會打印。

2

使用Array#each

(1..10).methods.each {|m| puts m}