マイペースなRailsおじさん

Ruby、Ruby on Rails、オブジェクト指向設計を主なテーマとして扱います。だんだん大きくなっていくRuby on Rails製プロダクトのメンテナンス性を損なわない方法を考えたり考えなかったりしている人のブログです。

`break` terminates smallest loop and overrides return value.

As you know break terminates loop. Below code execute the block only once. And return nil.

[1, 2, 3].each { |n| break } # => nil

break can have 1 argument. If the argument was given, the value will be used as the return value of evaluation of the method which use the block.

It is possible to return not Array value as the return value of map or select.

each = [1, 2, 3].each { |n| break n }
map = [1, 2, 3].map { |n| break n }
select = [1, 2, 3].select { |n| break n }

pp each # => 1
pp map # => 1
pp select # => 1