0
0
Rubyprogramming~5 mins

Explicit return statement in Ruby

Choose your learning style9 modes available
Introduction

We use an explicit return statement to clearly say what value a method should give back when it finishes.

When you want to stop a method early and send back a value.
When you want to make your code easier to read by showing the return value clearly.
When you have multiple places in a method that can send back different results.
When you want to return a value before the method reaches the end.
Syntax
Ruby
def method_name
  # some code
  return value_to_return
end

The return keyword immediately ends the method and sends back the value.

If you don't use return, Ruby automatically returns the last evaluated expression.

Examples
This method returns a greeting message explicitly using return.
Ruby
def greet(name)
  return "Hello, #{name}!"
end
Returns early if the number is less than 10, otherwise returns a different message.
Ruby
def check_number(num)
  return "Too small" if num < 10
  "Large enough"
end
Returns the sum of two numbers explicitly.
Ruby
def add(a, b)
  sum = a + b
  return sum
end
Sample Program

This program checks if a number is even. It uses return to send back a message early if the number is even.

Ruby
def find_even(number)
  return "Even number found!" if number.even?
  "Not an even number"
end

puts find_even(4)
puts find_even(7)
OutputSuccess
Important Notes

Using return can make your code clearer, especially in longer methods.

Remember, return stops the method immediately, so code after it won't run.

Summary

Explicit return tells Ruby exactly what value to send back from a method.

It helps stop the method early and makes your code easier to understand.

You can use it anytime you want to return a value before the method ends.