568 views
What's the return value of the following Ruby code?
(1..10).each { |n| break n if n == 5 } # => ???
The correct answer is
nil
(1..10)
It raises LocalJumpError
5
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
(1..10).each { |n| break n if n == 5 } # => 5
Range Creation: (1..10)
Iteration: .each { |n| ... }
each
method is called on the Range object. each
iterates over each element in the range, passing each element to the block as n
.Block Execution: { |n| break n if n == 5 }
n
in the range, the block executes the code inside it. The block checks if n
is equal to 5. If the condition is met (n == 5
), the break
keyword is executed with the argument n
.break
Keywordbreak
is used to exit a loop or iterator early.break
is called, it immediately terminates the loop or iteration and returns the value provided to break
as the result of the entire loop or iterator.break
, it returns nil
.each
method starts iterating over the range (1..10)
.n
, the block checks if n
is equal to 5.n
is 1, 2, 3, or 4, the condition n == 5
is false, so the loop continues to the next iteration.n
is 5, the condition n == 5
is true, so break n
is executed.break n
statement exits the loop and returns the value of n
(which is 5) as the result of the entire each
method.(1..10).each { |n| break n if n == 5 }
returns 5
.break
If break
is used without an argument, it returns nil
by default:
result = (1..10).each { |n| break if n == 5 } puts result # => nil
n
is 5, break
is called without an argument.nil
as the result of the each
method.You can provide a custom argument to break
to return a specific value:
result = (1..10).each { |n| break 42 if n == 5 } puts result # => 42
n
is 5, break 42
is executed.42
as the result of the each
method.break
keyword is used to exit a loop or iterator early.break
returns nil
if no argument is provided.break
to return a specific value.(1..10).each { |n| break n if n == 5 }
, the loop exits when n
is 5, returning 5
as the result.Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©