Menu
Coddy logo textTech

Return Values

Part of the Fundamentals section of Coddy's Ruby journey — lesson 50 of 88.

So far, our methods have performed actions like printing output. But methods become truly powerful when they can send data back to the code that called them. This is what return values are for.

In Ruby, a method automatically returns the value of its last expression:

def add(a, b)
  a + b
end

result = add(5, 3)
puts result  # Outputs: 8

Notice there's no puts inside the method. Instead, the method calculates a + b and returns that value. We can then store it in a variable or use it directly.

You can also use the return keyword explicitly:

def multiply(a, b)
  return a * b
end

puts multiply(4, 5)  # Outputs: 20

The return keyword immediately exits the method and sends back the specified value. This is useful when you want to exit early based on a condition. Both approaches work, but Ruby programmers often rely on implicit returns for cleaner code.

Return values let you chain operations and build complex logic from simple methods:

def double(n)
  n * 2
end

puts double(double(3))  # Outputs: 12
challenge icon

Challenge

Easy

Define a method called square that takes one parameter n and returns the square of that number (the number multiplied by itself).

Read two integers from input. Use the square method to calculate the square of each number, then print the sum of both squares.

For example, if the inputs are 3 and 4:

  • Square of 3 is 9
  • Square of 4 is 16
  • Sum is 25

The output should be:

25

If the inputs are 5 and 2, the output should be:

29

Cheat sheet

Methods can return values to the code that called them. In Ruby, a method automatically returns the value of its last expression:

def add(a, b)
  a + b
end

result = add(5, 3)
puts result  # Outputs: 8

You can also use the return keyword explicitly to exit the method and send back a value:

def multiply(a, b)
  return a * b
end

puts multiply(4, 5)  # Outputs: 20

Return values allow you to chain method calls:

def double(n)
  n * 2
end

puts double(double(3))  # Outputs: 12

Try it yourself

# Read two integers from input
num1 = gets.chomp.to_i
num2 = gets.chomp.to_i

# TODO: Define the square method below


# TODO: Calculate the sum of squares using the square method and print the result
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals