ruby map, reduce, select, reject, group_by
a = %w(a b cD)
map:
针对每个element进行变换并返回整个修改后的map
a.map do |item|
a.upcase
end
a.map(&:upcase) 一样的效果, &:代表了item, 太简洁了,但格式难记。
reduce:
把array变换为一个值后返回。
a.reduce(:+) #=> "abcD"
(5..10).reduce(0) do |sum, value|
sum + value
end
等于 (1..100).reduce(:+)
reduct(0)里面的0是代表sum的初始值
select:
根据条件返回一个子集
(1..8).select { |x| x % 2 == 0 } #=> [2, 4, 6, 8]
reject:
根据条件剔除一个子集
(1..8).reject { |x| x % 2 == 0 } #=> [1, 3, 5, 7] group_by: 根据条件组成Map
langs.group_by { |lang| lang[0] } #=> {"r"=>["ruby"], "p"=>["python", "perl"]}
a=%w(chenxiao chenmin chensiheng xiaochen liyulong)
a.group_by{|item| item.index("chen") != nil} false=>["liyulong"],
true=>["chenxiao", "chenmin", "chensiheng", "xiaochen"]
Ruby you are the best friend of programmer!