Ruby Language Reference

break statement

Break in While

Terminates a while/until loop.

song = %w(singing in the rain done)
index = 0

while index < song.length
  word = song[index]

  break if word == 'done'

  index += 1
  puts "Currently singing the word: #{word}"
end

This prints:

Currently singing the word: singing
Currently singing the word: in
Currently singing the word: the
Currently singing the word: rain

Break in Until

i = 0
until i == 3
  p "The value of i is : #{i}"
  i += 1
  break if i == 2
end

This prints:

The value of i is : 0
The value of i is : 1

Break Inside a Method with a Block

def test
  yield
end

result = test { break }

p result

This prints nil. The 'break`statement terminates a method with an associated block if called within the block.


Sharing is Caring