LoginSignup
11
3

More than 3 years have passed since last update.

Rubyのeach_with_objectの途中でbreakした時に困った話

Last updated at Posted at 2019-06-08

以下のようなコードを実行しようとして失敗した話

arr = (1..1000).each_with_object([]) do |num, arr|
    arr << num
    break if num == 500
end

p arr #=> nil

なんとなく上記のようなコードを実行したらarrの中には1..500までの値を保持した配列が返ってくると思ったが、実際にはnilが返ってきた。

どうやらeach_with_objectは最後までループを実行しきって、初めて値を返すようで、
ループの実行途中にbreak文を挟んでしまうと、そこまでの値を返すのではなくnilになってしまうみたい。

上記のような問題に対しての解決策は簡単で、(僕はしらなかったが)実は、breakは引き数を持たせることができる。
breakに対して引数を持たせてあげることで、今回のような場合でも戻り値をnilではなく引き数の値とすることができる。

arr = (1..1000).each_with_object([]) do |num, arr|
    arr << num
    break arr if num == 500
end

p arr #=> [1, 2, 3, .. 498, 499, 500]
11
3
1

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
11
3