Method Return Values11:42 with Jay McGavren
Ruby methods have a return value, a value they send back to the code that called them. Let's experiment with return values.
- Ruby methods have a return value, a value they send back to the code that called them.
def add(first, second) return first + second end def subtract(first, second) return first - second end total = add(1, 2) puts total remaining = subtract(8, 3) puts remaining
- We don't need the
returnkeywords here - the last expression evaluated in a method becomes that method's return value.
def add(first, second) first + second end def subtract(first, second) first - second end total = add(1, 2) puts total remaining = subtract(8, 3) puts remaining
- Pass return values to other functions
# We don't have to assign the return value to a variable first. # We can just pass it straight to "puts". puts add(1, 2) puts subtract(8, 3) # We can also use method return values as arguments to our own methods. puts add(add(1, 2), 4) puts add(3, subtract(11, 7)) puts add(add(1, 2), subtract(11, 7))
Returning a value vs. using
- It's important to distinguish between method output using
putsand a method return value.
- This works because
subtractreturns the result of the subtraction:
def subtract(first, second) first - second end number = 9 puts number # 9 number = subtract(number, 1) puts number # 8 number = subtract(number, 1) puts number # 7
- This doesn't work because
subtractreturns the result of calling
puts, which is an empty value:
def subtract(first, second) puts first - second # Returns an empty value! end number = 9 puts number # 9 number = subtract(number, 1) # Assigns empty value to "number"! puts number # Prints empty value! number = subtract(number, 1) # Tries to subtract from empty value, resulting in error! puts number # Never runs because of the error!
Widget store code
Here's our widget store code, with the
ask method updated to return what the user types.
def ask(question) print question # "gets" returns a string the user types. # Because the call to "gets" is the last # expression in the "ask" method, the # return value of "gets" becomes the # return value of "ask". gets end puts "Welcome to the widget store!" answer = ask("How many widgets are you ordering?") puts answer # Prints whatever the user typed.
We've created a workshop where you can get additional practice defining Ruby methods. Don't miss this chance to strengthen your skills; it will make later stages easier!
Visit the workshop here: Practice Ruby Methods
Let's get back to our Widget Store program. 0:00 We're still working on asking the user how many widgets they want to order and 0:02 storing the number they enter. 0:05 Now that we know how to write methods and pass arguments to them, 0:07 we know most of what we need to add this feature. 0:11 Let's give it a try now. 0:13 We'll define a new ask method that takes a question 0:14 parameter in the form of a string. 0:19 Make sure to type an end keyword to end your method definition. 0:22 And for now let's simply call the print method within the ask method body and 0:27 pass it the question, we got us a parameter. 0:34 And following our welcome to the widget store method, 0:38 let's make a call to this new ask method. 0:41 We'll call ask and then here in parenthesis we'll pass a string. 0:44 And in that string, we'll say, how many widgets are you ordering? 0:49 Let's save that and try running it with ruby widgets.rb. 0:59 And we can see our output down here in the terminal. 1:04 As before we've got our welcome message welcome at the widget store. 1:07 And then here's the results of our call to the ask method up here. 1:11 We pass at the string how many widgets are you ordering? 1:15 And that gets printed down here. 1:18 Notice that it's not skipping to a new line after printing the question that's 1:20 because we're calling the print method instead of put S method. 1:24 The reason for that will become clear shortly. 1:27 Now we need to get the text that the user enters at the keyboard, 1:29 the gets method can do that for us. 1:34 When we call gets it waits for the user to type something and 1:36 press enter and then returns what the user types. 1:40 In this version of ask, 1:43 we'll just assign the value the user typed to a variable answer. 1:45 We'll name our variable answer and we'll assign it the return value from gets. 1:50 And then we'll simply print that value. 1:55 So we'll save that and try running it. 2:01 And as before, it'll print out the question that it's asking us. 2:03 How many widgets are you ordering? 2:09 And now it's waiting for us to type some input in the keyboard. 2:11 And that's why we used a print method to print the question instead of put s which 2:14 would skip down to the next line. 2:19 Our input is going to appear here on the same line as the question. 2:20 So now we can type whatever we want here at the prompt. 2:25 So I'll use a value of 8 and press Enter when I'm done. 2:28 And the value that I typed will get returned from the gets method, 2:32 assigned to the answer variable, and then that will get passed to 2:37 the puts method called down here, and printed out to the console. 2:41 So we typed 8, and it prints 8. 2:45 So how does this work exactly? 2:49 Well, Ruby methods have a return value, 2:51 a value that they send back to the code that called them. 2:53 Here, the return value from gets is getting assigned to the variable answer. 2:56 Let's take a look at return values in another context though. 3:02 Here are our add and subtract methods from before. 3:05 First I'm going to get rid of this first line here, which prints out the parameters 3:08 that they receive cuz we don't really need that code anymore. 3:13 Now currently the add and subtract methods just print the result of adding or 3:16 subtracting their first and second parameters. 3:21 But let's modify these methods so that they use a return value instead. 3:24 I'm going to remove the call to puts and then its place, 3:28 I'm going to use the returning keyword. 3:32 Following the return keyword is an argument that you want to 3:36 return to the method caller. 3:40 So in this case, we'll just use the exact same code that we did previously. 3:43 We'll add the first and second parameters and return that value. 3:47 Down here I'll remove the call to puts and I'll use a return keyword there as well. 3:50 Let's try running this. 3:56 Ruby parameters.rb and we don't get any output right at first that's 4:02 because the return keyword doesn't print a value or 4:07 do anything besides pass it back to the code that called it. 4:11 In order to actually see the output again we're going to need to do something with 4:15 those return values down here in the place that we're calling these methods. 4:19 So this call to the add method here is actually returning a value right now. 4:24 It's calling the result of adding its first and second parameters. 4:28 But we're not actually doing anything with that return value. 4:32 So I'm going to take the return value and pass it to puts method down here. 4:35 If we save that and try running it. 4:40 This time we'll see output. 4:42 We'll see the return value that we're getting from the add function, 150. 4:45 Let's do the same for the remaining method calls. 4:49 So puts subtract, puts add, puts subtract. 4:51 Try running it again. 4:57 And this time you can see that all four of our method calls are returning values and 4:59 then we're printing them out down here. 5:04 We don't actually need the return keywords here though. 5:07 The last expression evaluated in a method becomes that method's return value. 5:10 So if we were to remove the return keyword here, first plus second would be 5:15 the last expression evaluated within the add methods body, and 5:20 that would become the methods return value you. 5:24 So let's remove the return keyword from add, and 5:27 we can remove the return keyword from subtract as well 5:30 because this expression will the return value of the subtract method. 5:33 And if we try running this, it'll behave in just the same way it did before. 5:37 There's a variety of things you can do with Ruby return values. 5:44 You can either take the return value and pass it directly to another 5:48 method as we're doing with puts in our add and subtract methods here. 5:51 Or you can assign a return value to a variable first, if you prefer. 5:55 So for example, we can assign the return value from add here to 5:59 a total variable, and then print that out if we want. 6:04 Save that, try running it. 6:08 And you can see that the end result is the same here. 6:09 We take our first call to add. 6:13 It's return value is going to be 150. 6:16 We assign that to the total variable and then print that out here. 6:18 And you can see a 150 in our results down here. 6:21 We can also use method return values as arguments store our own methods. 6:24 So for example, I can take the return value from calling add 1 and 6:29 2, and I can pass that back to the add method as an argument. 6:34 So add 1 and 2 will give us three, we can add 3 and 4 like this. 6:39 Let's try saving that, and running it. 6:46 Whoops, I forgot to call puts with that return value. 6:52 Let me go back up into the code and have that there. 6:54 And that's we had no output. 6:56 Let's see if we get output this time. 6:58 There we go. 6:59 The result of adding 1 and 2 is 3, and the result of adding that to 4 is 7. 7:01 You can see that in the output down here. 7:07 Let's try making another call to add. 7:09 And this time we'll take the number 3 and we'll add the results of subtracting. 7:12 11 and 7, 7:22 try running that. 7:26 And the results of subtracting 7 from 11 is 4 if we add that to 3, 7:30 the result is 7 again. 7:36 It's very important not to confuse a method returning a value 7:38 with if printing a value using puts. 7:43 So let's take our subtracts method here and let's pass a variable to it. 7:45 We'll declare a variable named number and we'll assign it a value of 9. 7:50 We'll print out of the value it contains. 7:55 And then we'll reassign to that variable the result of calling the subtract method. 7:58 A little typo there, let me correct that. 8:10 And we'll call the subtract method with the value currently in number. 8:12 And the number 1, which will subtract 1 from whatever's in number and 8:16 assign that back to number. 8:22 So number should contain 8 after this, and let's copy and 8:25 paste that code so that we do it again a second time. 8:29 And then with printing the final value in the number variable. 8:33 Okay, let's try running this. 8:37 And we see 9, 8, 7 as our output. 8:42 We start with 9, subtract 1 and get 8, subtract 1 again and get 7. 8:45 But suppose that instead of returning a value, the subtract method 8:49 printed the result of subtracting its second argument from its first. 8:53 This will actually return an empty value from the subtract method. 8:57 So lets try running this, and it appears to work correctly at first. 9:02 It prints out the value and our number variable 9, and 9:07 then it appears to subtract 1 from it giving us 8 and printing that out. 9:10 But what's actually happening here, 9:14 is that the call to puts is returning an empty value. 9:16 And that's what gets assigned to the number variable down here. 9:19 Then when we try to call subtract with number, which now contains this empty 9:22 value, we get an undefined method minus for nil class, that is an empty value. 9:28 So make sure not to confuse a method calling puts with returning a value. 9:33 In many cases a method will only work correctly if it actually returns a value. 9:38 So now that we actually understand method return values a bit better, 9:43 let's update our ask method to use them. 9:47 Instead of taking the value return from gets and 9:50 assigning it to a variable and then printing that variable out, 9:53 let's simply return the user's input from the ask method. 9:57 We'll assign that return value to a variable named answer down here. 10:00 And then after that we'll print the value that the answer variable holds. 10:06 This way we'll be able to do other things with the users response out 10:10 here in the main code. 10:15 Let's say then and try running it. 10:17 Ruby widets.rb and it'll ask us how many widgets are you ordering? 10:22 Let's say 8. 10:26 And as before it will print out value that we input of 8. 10:27 We've completed the second feature for our program. 10:33 We ask the user which quantity of widgets they want, call the gets method to get 10:36 their keyboard entry, and store the return value from gets in a variable. 10:41 Learning the call methods was the key to getting this far in your program. 10:45 Practicing your new skills is important to making them stick. 10:49 So be sure to check the teacher's notes on this video for some practice ideas. 10:53 You're off to a great start learning Ruby. 10:57 You've learned the call methods and to use their return values. 11:00 You've even learned to write your own methods. 11:03 Those skills would be useful in pretty much every program you write. 11:05 And now, you can also store values in variables when you need to, 11:10 that's another skill you'll be using a lot. 11:13 There's just one minor issue with the program. 11:16 When we ask the user how many widgets they want to buy, 11:19 our question runs right up against the place their keyboard input is shown. 11:22 That looks a little less than professional. 11:26 To fix this, we're going to need to learn more about strings. 11:29 Just like most other programming languages, 11:33 Ruby uses strings to store text. 11:36 We'll learn all about them in the next stage. 11:38 See you there. 11:41
You need to sign up for Treehouse in order to download course files.Sign up