break can return a value

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

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

Explanation of the Code

(1..10).each { |n| break n if n == 5 } # => 5

  1. Range Creation: (1..10)

    • This creates a Range object representing the sequence of numbers from 1 to 10, inclusive.
  2. Iteration: .each { |n| ... }

    • The each method is called on the Range object. each iterates over each element in the range, passing each element to the block as n.
  3. Block Execution: { |n| break n if n == 5 }

    • For each element 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.

The break Keyword

  • Definition: break is used to exit a loop or iterator early.
  • Interaction with Scope: When 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.
  • Default Behavior: If no argument is provided to break, it returns nil.

Detailed Breakdown of the Code

  • The each method starts iterating over the range (1..10).
  • For each number n, the block checks if n is equal to 5.
  • When n is 1, 2, 3, or 4, the condition n == 5 is false, so the loop continues to the next iteration.
  • When n is 5, the condition n == 5 is true, so break n is executed.
  • The break n statement exits the loop and returns the value of n (which is 5) as the result of the entire each method.
  • Thus, the code (1..10).each { |n| break n if n == 5 } returns 5.

Example with Default Return Value of 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

  • Here, when n is 5, break is called without an argument.
  • This causes the loop to exit and return nil as the result of the each method.

Example with Custom Return Value

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

  • In this example, when n is 5, break 42 is executed.
  • This causes the loop to exit and return 42 as the result of the each method.

Summary

  • The break keyword is used to exit a loop or iterator early.
  • By default, break returns nil if no argument is provided.
  • You can provide an argument to break to return a specific value.
  • In the example (1..10).each { |n| break n if n == 5 }, the loop exits when n is 5, returning 5 as the result.

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©