0
0
Rubyprogramming~5 mins

Implicit return (last expression) in Ruby

Choose your learning style9 modes available
Introduction

In Ruby, methods automatically give back the result of the last thing they do. This means you don't have to write return every time.

When you want your method to send back a value without extra words.
When writing simple methods that just calculate and give a result.
When you want cleaner and shorter code.
When you want to avoid mistakes by forgetting to write <code>return</code>.
When you want your code to be easy to read like a story.
Syntax
Ruby
def method_name
  last_expression
end

The last expression inside the method is automatically returned.

You can still use return if you want to exit early.

Examples
This method adds two numbers and returns the sum without using return.
Ruby
def add(a, b)
  a + b
end
This method returns a greeting string as the last expression.
Ruby
def greet(name)
  "Hello, #{name}!"
end
The last expression inside the if block is returned automatically.
Ruby
def check_number(num)
  if num > 0
    "Positive"
  else
    "Not positive"
  end
end
Sample Program

This program defines a method that multiplies two numbers and returns the product implicitly. Then it prints the result.

Ruby
def multiply(x, y)
  x * y
end

result = multiply(4, 5)
puts "The result is: #{result}"
OutputSuccess
Important Notes

Implicit return makes Ruby code shorter and easier to read.

If you put return explicitly, it will override the implicit return.

Only the last expression is returned, so make sure it is what you want to send back.

Summary

Ruby methods return the last expression automatically.

You don't need to write return unless you want to exit early.

This feature helps keep code clean and simple.