You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
+
breakif i ==3
9
+
10
+
puts i
11
+
end
12
+
# Output:
13
+
# 0
14
+
# 1
15
+
# 2
16
+
```
17
+
18
+
The `break` statement can be used with any of Ruby's iteration methods or loops.
19
+
20
+
```ruby
21
+
# Using break with different types of loops
22
+
array = [1, 2, 3, 4, 5]
23
+
24
+
# With each
25
+
array.each do |num|
26
+
breakif num >3
27
+
28
+
puts"Number: #{num}"
29
+
end
30
+
# Output:
31
+
# Number: 1
32
+
# Number: 2
33
+
# Number: 3
34
+
35
+
# With infinite loop
36
+
i =0
37
+
loopdo
38
+
i +=1
39
+
breakif i >=5
40
+
41
+
puts"Count: #{i}"
42
+
end
43
+
```
44
+
45
+
## Break with a Value
46
+
47
+
When used inside a block, `break` can return a value that becomes the result of the method call.
48
+
49
+
```ruby
50
+
# Using break with a return value
51
+
result = [1, 2, 3, 4, 5].map do |num|
52
+
break"Too large!"if num >3
53
+
54
+
num *2
55
+
end
56
+
puts result # Output: "Too large!"
57
+
58
+
# Break in find method
59
+
number = (1..100).find do |n|
60
+
break n if n >50&& n.even?
61
+
end
62
+
puts number # Output: 52
63
+
```
64
+
65
+
## Break in Nested Loops
66
+
67
+
When using `break` in nested loops, it only exits the innermost loop unless explicitly used with a label (not commonly used in Ruby).
68
+
69
+
```ruby
70
+
# Break in nested iteration
71
+
result = (1..3).each do |i|
72
+
puts"Outer loop: #{i}"
73
+
74
+
(1..3).each do |j|
75
+
breakif j ==2
76
+
77
+
puts" Inner loop: #{j}"
78
+
end
79
+
end
80
+
# Output:
81
+
# Outer loop: 1
82
+
# Inner loop: 1
83
+
# Outer loop: 2
84
+
# Inner loop: 1
85
+
# Outer loop: 3
86
+
# Inner loop: 1
87
+
88
+
# Breaking from nested loops using a flag
89
+
found =false
90
+
(1..3).each do |i|
91
+
(1..3).each do |j|
92
+
if i * j ==4
93
+
found =true
94
+
break
95
+
end
96
+
end
97
+
breakif found
98
+
end
99
+
```
100
+
101
+
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