0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

好きな引数を指定してループを回せるeach_with_objectについて

Last updated at Posted at 2025-03-02

引数に渡したオブジェクトをループ処理の中でアクセスし、レシーバーの要素の数だけループを回す事ができる。

公式では配列を引数に取り、それにpushしていく使い方が紹介されているが、{}をオブジェクトにとって、以下のような使い方も可能
https://docs.ruby-lang.org/ja/latest/method/Enumerable/i/each_with_object.html

# evens = (1..10).each_with_object([]) {|i, a| a << i*2 } # 配列の場合はこんな感じ
evens = (1..10).each_with_object({}) {|i, h| h[i] = i*2 } # ハッシュの場合はこんな感じでも使える。最後に引数で指定したハッシュオブジェクトを指定する

p evens # {1=>2, 2=>4, 3=>6, 4=>8, 5=>10, 6=>12, 7=>14, 8=>16, 9=>18, 10=>20}
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?