2012年10月26日 星期五

[Ruby]Using select, reject, collect, inject , detect and flatten.

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

結果:
1
2
3
4
=> [1, 2, 3, 4]

each a.each do |n| puts n end 
結果:
1
2
3
4
=> [1, 2, 3, 4]

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

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

collect a = [1,2,3,4] a.collect {|n| n*n}
結果:
=> [1, 4, 9, 16]

inject a = [1,2,3,4] a.inject {|acc,n| acc + n}
結果:
=> 10

inject a = [1,2,3,4] a.inject(15) {|acc,n| acc + n}
結果:
=> 25

inject a = [1,2,3,4] a.inject([]) {|acc,n| acc << n}
結果:
=> [2, 4, 6, 8]

detect a = [1,2,3,4] a.detect {|n| n == 3}
結果:
=> 3

flatten a = [1,[2,2,[3,4],5],[6,7]] p a.flatten #=> [1, 2, 2, 3, 4, 5, 6, 7] a.flatten! #=> [1, 2, 2, 3, 4, 5, 6, 7]
結果:
=> 3

參考來源:

http://www.namaraii.com/rubytips/?%C7%DB%CE%F3

【下列文章您可能也有興趣】

沒有留言: