A title for your blog

Ruby break takes an expression

I was reading some Rust code today and I found out that break in Rust can return a value. I thought this was a really useful feature and I wondered if Ruby was the same. Sure enough

 irb
irb(main):001* (0..10).each do |i|
irb(main):002*   p i
irb(main):003*   break "broke" if i > 5
irb(main):004> end
0
1
2
3
4
5
6
=> "broke"
irb(main):005* (0..10).each do |i|
irb(main):006*   p i
irb(main):007*   break if i > 5
irb(main):008> end
0
1
2
3
4
5
6
=> nil
irb(main):009>

TIL. Rust can also have labelled loops so break can say which loop it wants to break from. This isn’t available in Ruby.

#ruby #rust #snippets