enum.collect {| obj | block } => array
enum.map {| obj | block } => array
Returns a new array with the results of running block once for every element in enum.
(1..4).collect {|i| i*i } #=> [1, 4, 9, 16]
(1..4).collect { "cat" } #=> ["cat", "cat", "cat", "cat"]
모든 요소가 블럭을 실행후 새로운 배열을 return한다.
enum.detect(ifnone = nil) {| obj | block } => obj or nil
enum.find(ifnone = nil) {| obj | block } => obj or nil
Passes each entry in enum to block. Returns the first for which block is not false.
If no object matches, calls ifnone and returns its result when it is specified, or returns nil
(1..10).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> nil
(1..100).detect {|i| i % 5 == 0 and i % 7 == 0 } #=> 35
find는 detect의 별칭이다. 각각의 요소를 블럭에 적용하고 결과가 true인 첫번째 값을 반환한다.
enum.inject(initial) {| memo, obj | block } => obj
enum.inject {| memo, obj | block } => obj
Combines the elements of enum by applying the block to an accumulator value (memo) and each element in turn.
At each step, memo is set to the value returned by the block. The first form lets you supply an initial value
for memo. The second form uses the first element of the collection as a the initial value
(and skips that element while iterating).
# Sum some numbers
(5..10).inject {|sum, n| sum + n } #=> 45
# Multiply some numbers
(5..10).inject(1) {|product, n| product * n } #=> 151200
# find the longest word
longest = %w{ cat sheep bear }.inject do |memo,word|
memo.length > word.length ? memo : word
end
longest #=> "sheep"
# find the length of the longest word
longest = %w{ cat sheep bear }.inject(0) do |memo,word|
memo >= word.length ? memo : word.length
end
longest #=> 5
요소들 각각에 값을 차례로 블럭에 적용후 memo에 적용하며, memo에 초기값을 설정할 수 있다.
[출처 : http://www.ruby-doc.org/core/]