官术网_书友最值得收藏!

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:

  1. Create a new Ruby file. Define the method and the return variables:

    def array_stats(input_array)

      return sum, median, mean

    end

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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.

主站蜘蛛池模板: 扶沟县| 凉城县| 奉新县| 长垣县| 佛山市| 荆州市| 樟树市| 公主岭市| 普陀区| 建昌县| 齐齐哈尔市| 湄潭县| 望城县| 邹平县| 稷山县| 乐都县| 宜阳县| 军事| 平陆县| 兴安盟| 凌云县| 大同市| 镇康县| 宁武县| 新郑市| 翁源县| 合阳县| 巨鹿县| 赣榆县| 英德市| 平塘县| 宜兰县| 永福县| 肇州县| 雅江县| 吴江市| 鹤峰县| 万州区| 虹口区| 庆元县| 扬中市|