#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"]}
両者の主な違いの一つは、#inject
セット反復ごとにブロックで返される値に等しいmemo
ながら全体を通して反復memo
を追跡#each_with_object
あります。
もう1つの違いは、順序またはブロックパラメータです。
ここにはいくつかの意向がありますか? 2つの同様の方法のブロックパラメータを逆にすることは意味がありません。
よろしくお願いします。私は、[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)と[列挙子#each_index](ブロック変数の配置における)の一貫性http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-each_with_index)も要因となっている可能性があります。 –
"引数の順序はメソッド名の字句順を反映しています。これは' each ... object'です。 "...............私は常に順序を忘れてしまいました。 –