Ruby 一起来学 Enumerable 吧

chenge · January 24, 2016 · Last by ywencn replied at February 01, 2016 · 2249 hits

我印象中最常用的两个模块是 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 开始吧,陆续补充。

slice 方法系列的例子:slice_when

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]

chunk 分块

返回的是 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]]
#...

group_by 分组

返回 hash,分组到不同的 key。

 (1..6).group_by { |i| i % 3 }    
# { 1=>[1, 4], 2=>[2, 5], 0=>[3, 6] }

entries = to_a

好多很有用,就是真到用的时候想不起来。。。

You need to Sign in before reply, if you don't have an account, please Sign up first.