Programing

Ruby에서 각각과 collect 메소드의 차이점

lottogame 2020. 11. 30. 07:39
반응형

Ruby에서 각각과 collect 메소드의 차이점


이 질문에 이미 답변이 있습니다.

이 코드에서 나는 두 가지 방법의 차이를 알고하지 않습니다 collecteach.

a = ["L","Z","J"].collect{|x| puts x.succ} #=> M AA K 
print  a.class  #=> Array

b = ["L","Z","J"].each{|x| puts x.succ} #=> M AA K
print  b.class #=> Array

Array#each배열을 취하고 모든 항목에 주어진 블록을 적용합니다. 배열에 영향을주지 않거나 새 객체를 생성하지 않습니다. 항목을 반복하는 방법 일뿐입니다. 또한 self를 반환합니다.

  arr=[1,2,3,4]
  arr.each {|x| puts x*2}

2,4,6,8을 인쇄하고 무엇이든지 [1,2,3,4]를 반환합니다.

Array#collect과 동일 Array#map하고 모든 항목에 대한 코드의 주어진 블록을 적용하여 새로운 배열을 반환한다. 간단히 '시퀀스의 각 요소를 새 형식으로 투영합니다.'

  arr.collect {|x| x*2}

[2,4,6,8]을 반환합니다.

그리고 당신의 코드에서

 a = ["L","Z","J"].collect{|x| puts x.succ} #=> M AA K 

A는 배열이지만 실제로 닐의 배열이다 [닐, 닐, 닐] 때문에 puts x.succ반환 nil(AA M은 K를 출력하더라도).

 b = ["L","Z","J"].each{|x| puts x.succ} #=> M AA K

또한 배열입니다. 그러나 그 값은 self를 반환하기 때문에 [ "L", "Z", "J"]입니다.


Array#each각 요소를 가져 와서 블록에 넣은 다음 원래 배열을 반환합니다. Array#collect각 요소를 가져 와서 반환되는 새 배열에 넣습니다.

[1, 2, 3].each { |x| x + 1 }    #=> [1, 2, 3]
[1, 2, 3].collect { |x| x + 1 } #=> [2, 3, 4]

each배열을 반복하고 각 반복에서 원하는 것을 수행하려는 경우입니다. 대부분의 (필수적) 언어에서 이것은 프로그래머가 목록을 처리해야 할 때 도달 할 수있는 "모든 것에 맞는"망치입니다.

보다 기능적인 언어의 경우 다른 방법으로 할 수없는 경우에만 이러한 종류의 일반 반복을 수행합니다. 대부분의 경우 map 또는 reduce가 더 적합합니다 (루비에 수집 및 주입).

collect 하나의 어레이를 다른 어레이로 바꾸고 싶을 때

inject 배열을 단일 값으로 바꾸고 싶을 때


문서 에 따르면 다음은 두 가지 소스 코드 스 니펫입니다 .

VALUE
rb_ary_each(VALUE ary)
{
    long i;

    RETURN_ENUMERATOR(ary, 0, 0);
    for (i=0; i<RARRAY_LEN(ary); i++) {
        rb_yield(RARRAY_PTR(ary)[i]);
    }
    return ary;
}

# .... .... .... .... .... .... .... .... .... .... .... ....

static VALUE
rb_ary_collect(VALUE ary)
{
    long i;
    VALUE collect;

    RETURN_ENUMERATOR(ary, 0, 0);
    collect = rb_ary_new2(RARRAY_LEN(ary));
    for (i = 0; i < RARRAY_LEN(ary); i++) {
        rb_ary_push(collect, rb_yield(RARRAY_PTR(ary)[i]));
    }
    return collect;
}

rb_yield()블록에서 반환 한 값을 반환합니다 ( 메타 프로그래밍에 대한이 블로그 게시물 참조 ).

따라서 each단지 수율 복귀 일본어 배열 중에 collect새로운 배열을 만들고 그것에 블록의 결과를 푸시; 그런 다음이 새로운 배열을 반환합니다.

소스 스 니펫 : , 수집


The difference is what it returns. In your example above a == [nil,nil,nil] (the value of puts x.succ) while b == ["L", "Z", "J"] (the original array)

From the ruby-doc, collect does the following:

Invokes block once for each element of self. Creates a new array containing the values returned by the block.

Each always returns the original array. Makes sense?


Each is a method defined by all classes that include the Enumerable module. Object.eachreturns a Enumerable::Enumerator Object. This is what other Enumerable methods use to iterate through the object. each methods of each class behaves differently.

In Array class when a block is passed to each, it performs statements of the block on each element, but in the end returns self.This is useful when you don't need an array, but you maybe just want to choose elements from the array and use the as arguments to other methods. inspect and map return a new array with return values of execution of the block on each element. You can use map! and collect! to perform operations on the original array.


I think an easier way to understand it would be as below:

nums = [1, 1, 2, 3, 5]
square = nums.each { |num| num ** 2 } # => [1, 1, 2, 3, 5]

Instead, if you use collect:

square = nums.collect { |num| num ** 2 } # => [1, 1, 4, 9, 25]

And plus, you can use .collect! to mutate the original array.

참고URL : https://stackoverflow.com/questions/5347949/whats-different-between-each-and-collect-method-in-ruby

반응형