|
| 1 | +# Break |
| 2 | + |
| 3 | +In Ruby, the `break` keyword is used to exit a loop or block prematurely. Unlike `next` which skips to the next iteration, `break` terminates the loop entirely and continues with the code after the loop. |
| 4 | + |
| 5 | +```ruby |
| 6 | +# Basic break usage in a loop |
| 7 | +5.times do |i| |
| 8 | + break if i == 3 # Exit loop when i reaches 3 |
| 9 | + puts i |
| 10 | +end |
| 11 | +# Output: |
| 12 | +# 0 |
| 13 | +# 1 |
| 14 | +# 2 |
| 15 | +``` |
| 16 | + |
| 17 | +The `break` statement can be used with any of Ruby's iteration methods or loops. |
| 18 | + |
| 19 | +```ruby |
| 20 | +# Using break with different types of loops |
| 21 | +array = [1, 2, 3, 4, 5] |
| 22 | + |
| 23 | +# With each |
| 24 | +array.each do |num| |
| 25 | + break if num > 3 # Stop when number exceeds 3 |
| 26 | + puts "Number: #{num}" |
| 27 | +end |
| 28 | +# Output: |
| 29 | +# Number: 1 |
| 30 | +# Number: 2 |
| 31 | +# Number: 3 |
| 32 | + |
| 33 | +# With while loop |
| 34 | +i = 0 |
| 35 | +while true # Infinite loop |
| 36 | + i += 1 |
| 37 | + break if i >= 5 # Exit condition |
| 38 | + puts "Count: #{i}" |
| 39 | +end |
| 40 | +``` |
| 41 | + |
| 42 | +## Break with a Value |
| 43 | + |
| 44 | +When used inside a block, `break` can return a value that becomes the result of the method call. |
| 45 | + |
| 46 | +```ruby |
| 47 | +# Using break with a return value |
| 48 | +result = [1, 2, 3, 4, 5].map do |num| |
| 49 | + break "Too large!" if num > 3 |
| 50 | + num * 2 |
| 51 | +end |
| 52 | +puts result # Output: "Too large!" |
| 53 | + |
| 54 | +# Break in find method |
| 55 | +number = (1..100).find do |n| |
| 56 | + break n if n > 50 && n.even? |
| 57 | +end |
| 58 | +puts number # Output: 52 |
| 59 | +``` |
| 60 | + |
| 61 | +## Break in Nested Loops |
| 62 | + |
| 63 | +When using `break` in nested loops, it only exits the innermost loop unless explicitly used with a label (not commonly used in Ruby). |
| 64 | + |
| 65 | +```ruby |
| 66 | +# Break in nested iteration |
| 67 | +result = (1..3).each do |i| |
| 68 | + puts "Outer loop: #{i}" |
| 69 | + |
| 70 | + (1..3).each do |j| |
| 71 | + break if j == 2 # Only breaks inner loop |
| 72 | + puts " Inner loop: #{j}" |
| 73 | + end |
| 74 | +end |
| 75 | +# Output: |
| 76 | +# Outer loop: 1 |
| 77 | +# Inner loop: 1 |
| 78 | +# Outer loop: 2 |
| 79 | +# Inner loop: 1 |
| 80 | +# Outer loop: 3 |
| 81 | +# Inner loop: 1 |
| 82 | + |
| 83 | +# Breaking from nested loops using a flag |
| 84 | +found = false |
| 85 | +(1..3).each do |i| |
| 86 | + (1..3).each do |j| |
| 87 | + if i * j == 4 |
| 88 | + found = true |
| 89 | + break |
| 90 | + end |
| 91 | + end |
| 92 | + break if found |
| 93 | +end |
| 94 | +``` |
| 95 | + |
| 96 | +The `break` keyword is essential for controlling loop execution and implementing early exit conditions. It's particularly useful when you've found what you're looking for and don't need to continue iterating. |
0 commit comments