我印象中最常用的两个模块是 Enumerable 和 Kernel,值得熟悉。
Enumerable#methods:
all? drop_while find_index max partition sort_by
any? each_cons first max_by reduce take
chunk each_entry flat_map member? reject take_while
collect each_slice grep min reverse_each to_a
collect_concat each_with_index group_by min_by select to_h
count each_with_object include? minmax slice_after to_set
cycle entries inject minmax_by slice_before zip
detect find lazy none? slice_when
drop find_all map one? sort
each、map 这些大家都很熟悉了,从不太熟悉的 slice 开始吧,陆续补充。
a = [1, 2, 3, 100, 101, 102]
a.slice_when do |x, y|
(y - x) > 10
end.each { |x| puts x }
#[1, 2, 3]
#[100, 101, 102]
返回的是 enumerator,所以一般连用一个 each。
[3,1,4,1,5,9,2,6,5,3,5].chunk {|n|
n.even?
}.each {|even, ary|
p [even, ary]
}
#[false, [3, 1]]
#[true, [4]]
#...
返回 hash,分组到不同的 key。
(1..6).group_by { |i| i % 3 }
# { 1=>[1, 4], 2=>[2, 5], 0=>[3, 6] }