Step 23: Return & Break


Sometimes, based on certain conditions in our programs, we need to stop our methods or loops early. Ruby provides us with the return and break keywords to allow us to do this. return will cause a method to stop execution and return whatever is written next to the return in the code (default is nil). Normally, if there is no return keyword in a method, whatever is evaluated on the last line of the method is returned.

def print_even_numbers(arr)
     if arr.length == 0
        return "that array is empty!"
    end


    ind = 0


    while ind < arr.length
        if arr[ind] % 2 == 0
            puts(arr[ind])
        end

        ind = ind + 1
    end
end


puts(print_even_numbers([]))
puts(print_even_numbers([1, 3, 4, 7, 10]))

In the example above, the first thing we do is check to see if the array passed in actually has any values in it. If it doesn’t, we don’t bother running the rest of the method and just tell the caller that they screwed up.

break is similar, but it won’t return out of a method, it will just stop a loop.

def print_until_zero(arr)
    ind = 0
    while ind < arr.length
        if arr[ind] == 0
            break
        else
            puts(arr[ind])
            ind = ind + 1
        end
    end

    puts("all done")
end

print_until_zero([1, 3, 6, 2, 0, 14, 9, 7])

Above we can see that each number in the array is printed until 0 is found. When zero is found, the while loop is stopped prematurely, however the puts(“all done”) line at the end of the method still runs. If we had used return instead of break inside the while loop, that final line would not have been evaluated.