TL;DR
The main difference between your implementation is that youâre not actually returning the string, but only printing it to the screen. If the end goal is to return a value, then you should use the âreturnâ keyword instead of puts.
LONG VERSION
The article you linked to explains that when you donât use the keyword âreturnâ followed by what you want to return, Ruby will the last thing that was evaluated. In your case, the last thing evaluated is a puts statement which evaluates to ânil.â
So, I wouldnât say that your code is necessarily wrong, because it does what is intended, i.e., print the longer of the two strings; however, itâs not exactly what the âuserâ wanted. Since the user expects to be able to use âputsâ with the method, we should assume that they want the longer string returned, and not just the longer string printed. In your solution the userâs use of the âputsâ command doesnât actually do anything. Try this with your code:
test = longer_string(âappâ, âacademyâ) # => âacademyâ
puts("print the test variable after this line")
puts test
You might expect to get the longer string twice, once before the "print the test variable⌠" line and once after, or maybe you only expected to get it once after the âprint the test variableâŚâ line, but you only get it once before. This is because your code will always print the longer string whenever it is called, because your method specifically calls the âputsâ command. It doesnât print it twice because it doesnât return the value of the longer string. So the userâs use of the puts command doesnât actually print anything.
Instead of using âputs,â try using âpâ instead. Itâs yet another Ruby print command, but prints more information:
test = longer_string(âappâ, âacademyâ) # => âacademyâ
puts("print the test variable after this line")
p test
Here, youâll see that the last line prints ânil,â because that is what your code returned.
So, in the future, be cognizant of what the final outcome should be. If you simply what your method to print something and not return a value, then your code is perfect. If you want to be able to return a value, perhaps to store it in a variable for future use, then make sure you actually return the value using the âreturnâ keyword and not âputs.â