Using select, reject, collect, inject and detect.

参考链接:
http://queirozf.com/entries/ruby-map-each-collect-inject-reject-select-quick-reference

http://matthewcarriere.com/2008/06/23/using-select-reject-collect-inject-and-detect/

for 遍历数组 ,并打印出来每一个元素

code:

1
2
3
4
a = [1,2,3,4]
for n in a
puts n
end

这个可以 work,但 not very… Ruby.
下面这个才是,ruby 中的 iterator

each 遍历数组 ,并打印出来每一个元素

code:

1
2
3
a.each do |n|
puts n
end

Building a list of items from the array using select

select , 返回符合条件的 array

code:

1
2
a = [1,2,3,4]
a.select {|n| n > 2}

reject,返回不符合条件的 array

reject 当 n>2 为 false 时才会return

code:

1
2
a = [1,2,3,4]
a.reject {|n| n > 2}

collect,返回 运算 后的 array

code:

1
2
a = [1,2,3,4]
a.collect {|n| n*n}

Total the items in an array using inject

inject ,sum 所有元素并返回计算结果

code:

1
2
a = [1,2,3,4]
a.inject {|acc,n| acc + n}

inject with parameter,带初始参数,从参数开始累计,计算并返回

code:

1
2
a = [1,2,3,4]
a.inject(10) {|acc,n| acc + n}

inject return an array

code:

1
2
a = [1,2,3,4]
a.inject([]) {|acc,n| acc << n+n}

Find an item in the array using detect

detect 查找一项

code:

1
2
a = [1,2,3,4]
a.detect {|n| n == 3}

返回 3,如果没有找到,返回 nil