Ruby中Enumerable模块的一些实用方法

我在查看 Array 类和 Hash 类的祖先链的时候都发现了 Enumerable,说明这两个类都mixin了Enumerable模块。Enumerable模块为集合型类提供了遍历、检索、排序等方法(collect、map、each_with_index等),该模块的方法都用到了 each ,因此那些包含了本模块的类需要预先定义 each 。

Array.ancestors
# => [Array, Enumerable, Object, Kernel, BasicObject]
Hash.ancestors
# => [Hash, Enumerable, Object, Kernel, BasicObject]

一些实用小技巧:

chunk:将返回相同块值的连续元素组合在一起

示例一:

按相同日期分组
list = [{"date"=>"20180630","name"=>"a","times"=>20},
    {"date"=>"20180615","name"=>"b","times"=>20},
    {"date"=>"20180628","name"=>"c","times"=>20},
    {"date"=>"20180615","name"=>"a","times"=>20},
    {"date"=>"20180628","name"=>"b","times"=>20},
    {"date"=>"20180630","name"=>"c","times"=>20},
    {"date"=>"20180628","name"=>"a","times"=>20},
    {"date"=>"20180630","name"=>"b","times"=>20},
    {"date"=>"20180615","name"=>"c","times"=>20}
]
list.sort_by{|s| s["name"]}.sort_by{|s| s["date"] }.chunk{|x| x["date"]}.map(&:last)
# =>
# [
#    [{"date"=>"20180615", "name"=>"a", "times"=>20}, {"date"=>"20180615", "name"=>"b", "times"=>20}, {"date"=>"20180615", "name"=>"c", "times"=>20}], 
#    [{"date"=>"20180628", "name"=>"b", "times"=>20}, {"date"=>"20180628", "name"=>"c", "times"=>20}, {"date"=>"20180628", "name"=>"a", "times"=>20}], 
#    [{"date"=>"20180630", "name"=>"c", "times"=>20}, {"date"=>"20180630", "name"=>"b", "times"=>20}, {"date"=>"20180630", "name"=>"a", "times"=>20}]
# ] 

示例二:

#打印出带“def”的行
open("/Users/hhf/Desktop/work/projects/cloud-admin/app/models/user.rb") { |f|
  f.chunk { |line| line =~ /def/ }.each { |key, lines|
    p lines
  }
}

#带“def”的行单独打印出,其他行组合在一起打印 _alone使元素进入一个大块
open("/Users/hhf/Desktop/work/projects/cloud-admin/app/models/user.rb") { |f|
  f.chunk { |line| line =~ /def/ ? :_alone : true }.each { |key, lines|
    p lines
  }
}

chunk_while: 将块值为true的连续元素组合在一起,块值为false时切分元素

[1,2,4,9,10,11,12,15,16,19,20,21].chunk_while {|i, j| i+1 == j }.to_a
# => [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]

 

each_slice: 按给定的个数切分元素

a=[]
(1..10).each_slice(3) { |x| a << x }
p a
# => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

drop_while按指定条件删除元素,直到返回false时停止

a = [[1,3],[1],[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
a.drop_while { |x| x.count < 3 }
# => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]


猜你喜欢

转载自www.cnblogs.com/xiaoff/p/9402711.html