zed.0xff.me

Advanced Ruby: break(value) & next(value)

1. break(value)

break accepts a value that supplies the result of the expression it is “breaking” out of:

1
2
3
4
5
  result = [1, 2, 3].each do |value|
    break value * 2 if value.even?
  end

  p result # prints 4

2. next(value)

next accepts an argument that can be used the result of the current block iteration:

1
2
3
4
5
6
7
  result = [1, 2, 3].map do |value|
    next value if value.even?

    value * 2
  end

  p result # prints [2, 2, 6]