#each_with_object 및 #inject은 모두 해시를 작성하는 데 사용할 수 있습니다. 예를 들어#each_with_object와 #inject가 블록 매개 변수의 순서를 전환하는 이유는 무엇입니까?
: 둘 사이의 주요 차이점
matrix = [['foo', 'bar'], ['cat', 'dog']]
some_hash = matrix.inject({}) do |memo, arr|
memo[arr[0]] = arr
memo # no implicit conversion of String into Integer (TypeError) if commented out
end
p some_hash # {"foo"=>["foo", "bar"], "cat"=>["cat", "dog"]}
another_hash = matrix.each_with_object({}) do |arr, memo|
memo[arr[0]] = arr
end
p another_hash # {"foo"=>["foo", "bar"], "cat"=>["cat", "dog"]}
하나 #each_with_object
는 전체 반복을 통해 memo
추적 인 반면 #inject
세트의 각 반복에서, 블록에 의해 리턴 된 값 memo
동일.
또 다른 차이점은 순서 또는 블록 매개 변수입니다.
여기에 몇 가지 의도가 전달되어 있습니까? 두 가지 유사한 방법의 블록 매개 변수를 뒤집는 것은 의미가 없습니다.
좋은 흥미로운 이야기. [Enumerator # with_object] (http://ruby-doc.org/core-2.3.0/Enumerator.html#method-i-with_object)와 일관성이 있기를 바랍니다. 예를 들어. 'arr.each_with_index.with_object ({}) {| (e, i), h | ...'. 블록 변수'| h, (e, i) |'를 갖는 것은 매우 혼란 스러웠을 것입니다. –
[Enumerable # each_with_index] (http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-each_with_index)와 [Enumerator # each_index] (블록 변수 배치에서의 일관성) http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-each_with_index)도 요인이 될 수 있습니다. –
"인수의 순서는 메서드 이름의 어순 순서를 반영합니다. 각 이름은 'each ... object'입니다."........... 나는 항상 순서를 잊어 버리므로 결코 그렇게하지 않을 것입니다. –