- The Ruby Workshop
- Akshat Paul Peter Philips Dániel Szabó Cheyne Wallace
- 1054字
- 2021-06-11 13:04:42
Return Values
Methods are great for wrapping up blocks of code that accomplish some purpose. In many cases, we want to capture the results of that code execution in one or more variables. As such, the method can return these variables to the caller of the method. Conveniently enough, the keyword for returning variables is return.
Here is a basic case of adding two numbers:
def sum(var1, var2)
return var1 + var2
end
In Ruby, the value of the last line of code in a method is implicitly returned, so we also write this as follows:
def sum(var1, var2)
var1 + var2
end
total = sum(1, 3)
The choice to do one or the other depends on the developer's style and the requirements of the program.
The Ruby style guide says to avoid the use of the return keyword when not required for flow control.
Multiple Return Values
Ruby methods can also return multiple values. Let's take a look at some simple examples.
The following method returns a pair of random numbers:
def get_random_pair
return rand(10), rand(10)
end
There are a few ways to capture these return values:
pair = get_random_pair
item1, item2 = get_random_pair
As we can see, Ruby is smart enough to figure out what type of assignment we are trying to do. Ruby knows we have an array of two and we are trying to assign values to two variables. Let's see what happens when there is not a 1:1 ratio of return values to variable assignments:
def get_three_items
return rand(10), rand(10), rand(10)
end
item1, item2 = get_three_items
We can see here that Ruby put a single value for the item1 and item2 variables. The third item was discarded. If you run this code, you will see something similar to the following:

Figure 4.8: Multiple return values
IRB is outputting an array of three items. The method returns the three items no matter what, but Ruby can only assign them to two variables. However, the entire line of code still has a separate return value. We can demonstrate this with the following:
overall_return = (item1, item2 = get_three_items)
The output should be as follows:

Figure 4.9: The overall return value
This demonstrates that we can do variable assignment from the return value(s) of a method and still have an overall_return value from the whole statement. In most cases, the overall_return value is the same as the individual variable assignment; however, this demonstrates that it doesn't have to be, especially when you have multiple return values.
Also, as we can see, the overall_return value is an array, even though we listed the return values as a list of variables. This is because Ruby implements any set of multiple values as an array. Convenient, right? This means that we can also return an array and do the same thing with variable assignment and overall_return values.
We can list the return values in an array very easily using the Array#last method. Consider a basic array with five items:
array = [1,2,3,4,5]
We can use the following code to obtain the last two items from the array and assign them to a single variable:
top2 = array.last(2)
The output should be as follows:

Figure 4.10: Output for the array.last method
Use the following code to assign variables individually:
var1, var2 = array.last(2)
The output should be as follows:

Figure 4.11: Individual variable assignment
We can use the following code to assign variables individually, discarding the last item:
var1, var2 = array.last(3)
The output should be as follows:

Figure 4.12: Output after discarding the last item from an array
Until now, we have discussed the components of a method and how to implement them in Ruby. We have looked at various types of arguments and learned how to pass these arguments to methods. We also discussed how the return keyword can be used to capture the results from a method's execution in a variable. Now we will implement these concepts in an exercise.
Exercise 4.01: Performing Operations on an Array
In this exercise, we will be creating a method that returns the sum, mean, and median values of an array.
The following steps will help you to complete the exercise:
- Create a new Ruby file. Define the method and the return variables:
def array_stats(input_array)
return sum, median, mean
end
- Then, we define a method that will calculate the sum value using the inject method. The inject method is used to sequentially add values, one by one, from the array:
def array_stats(input_array)
sum = input_array.inject(0){|total, i| total + i }
return sum
end
- We modify the method that will calculate the mean value:
def array_stats(input_array)
sum = input_array.inject(0){|total, i| total + i }
mean = sum/input_array.length
return sum, mean
end
- Calculate median by creating another method that is dedicated to that purpose.
Note
The median is essentially the middle number in a sorted set of numbers. It is the value that separates the top half from the bottom half. As such, we need to write a method that calculates this. The median or middle number will depend on whether the set of numbers has an odd number or even number of elements.
Hence, we have used an if/else block in the method to address these two scenarios:
def calculate_median(array)
array = array.sort
if array.length.odd?
array[(array.length - 1) / 2]
else array.length.even?
(array[array.length/2] + array[array.length/2 - 1])/2.to_f
end
end
- Bring all the code together for sum, mean, and median:
def array_stats(input_array)
sum = input_array.inject(0){|total, i| total + i }
mean = sum/input_array.length
median = calculate_median(input_array)
return sum, mean, median
end
- Call sum, mean and median with different input arrays and capture the values into variables:
array_stats([1,2,3])
stats = array_stats([500, 12, 1, 99, 55, 12, 12])
sum, mean, median = array_stats([500, 12, 1, 99, 55, 12, 12])
The output should be as follows:
Figure 4.13: Output for sum, mean, and median
Note
The order of return values is important because they are similar to positional arguments. The order of how you list them will determine how they get assigned.
- SOA實踐
- Software Testing using Visual Studio 2012
- 深入淺出Spring Boot 2.x
- UI智能化與前端智能化:工程技術、實現方法與編程思想
- SQL Server 2016數據庫應用與開發習題解答與上機指導
- Reactive Android Programming
- Scientific Computing with Scala
- AppInventor實踐教程:Android智能應用開發前傳
- 微服務架構深度解析:原理、實踐與進階
- Extreme C
- Vue.js應用測試
- QGIS 2 Cookbook
- 計算機應用基礎案例教程(第二版)
- 深入理解Java虛擬機:JVM高級特性與最佳實踐
- INSTANT Premium Drupal Themes