总结 Enumerable 中一些常用的方法

2015/1/10 posted in  Ruby学习  

判断列表

all? any? none? one?如果有代码块,则以代码块的返回值判断;如果没有代码块,则用自身元素判断。

all? The method returns true if the block never returns false or nil

any? The method returns true if the block ever returns a value other than false or nil

none? The method returns true if the block never returns true for all elements

one? The method returns true if the block returns true exactly once

[1, 2, 3, 4].all? { |x| x<3 }   # false
[1, 2, 3, 4].any? { |x| x<3 }   # true
[1, 2, 3, 4].none? { |x| x<1 }  # true
[1, 2, 3, 4].none? { |x| x<1 }  # false

include?member? 是否包含某个元素

筛选列表中的元素

selectfind_all 选择代码块中为 true 的元素

[1, 2, 3, 4].select { |x| x < 3 }   # [1, 2]

reject 选择代码块中为 false 的元素

[1, 2, 3, 4].reject { |x| x < 3 }   # [3, 4]

detectfind Returns the first for which block is not false

[1, 2, 3, 4].detect{|x| x >2}    # 3
[1, 2, 3, 4].find(Proc.new { 0 }) { |x| x < 1 }   # 0

对列表中的元素进行操作

collectmap Returns a new array with the results of running block once for every element in enum.

[1, 2, 3, 4].map(&:to_s)    # ["1", "2", "3", "4"]

injectreduce

(5..10).reduce(:+)                            # 45
(5..10).inject {|sum, n| sum + n }            # 45
(5..10).reduce(0, :+)                         # 45
(5..10).inject{|max, x| max > x ? max : x }   # 10