看到好的ruby和rails代码收集在这儿
* select 配合 any?,用来做两层filter。map出来的array直接返回。map用于过滤等运算。
def monitored_paths
paths = Dir['**/*'].select do |path|
@script.patterns.any? {|p| path.match(p) }
end
paths.push(@script.path).compact!
paths.map {|path| Pathname(path).expand_path }
end
* reduce(inject)做积累运算,如把运算累积到一个新的array或hash中。
def to_hash
to_a.reduce({}){|hash,i| hash.store(i._id, i); hash}
end
tasks = pros.reduce([]) do |tasks, p|
tasks << p.get_task_with_ref(task_name)
end
#reduce方法比each,手工收集(累积要简约的多)
tasks = []
pros.each do |p|
task = p.get_task_with_ref(task_name)
tasks << task
end
本文分享了两个实用的Ruby编程技巧:一是使用`select`结合`any?`进行两层筛选并利用`map`进行数组处理;二是通过`reduce`(或`inject`)方法简化数组累积操作。
523

被折叠的 条评论
为什么被折叠?



