+ 2

Difference between return and print/puts??

What is the main mechanism behind these two? Let's suppose: def sum(a, b) puts a+b end x = sum(5, 23) puts x The same code can also be written as: def sum(a, b) return a+b end x = sum(5, 23) puts x

6th Mar 2017, 6:59 PM
Rohit Swami
Rohit Swami - avatar
3 Réponses
+ 8
'puts' or 'print' just prints out the value on the screen - that's it. 'return' assigns the result value to the function. You can do whatever you want with it - assign it to a variable or you use it calculations.
6th Mar 2017, 7:10 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
Ruby does, Python does NOT ('show the value of the last expression in your code')
6th Mar 2017, 7:33 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
print --> prints its argument. puts --> also prints its argument, but inserts a newline character at the end, so each argument (or each puts call) appears on its own line. return --> doesn’t print at all. The only reason you get the same output is that Ruby or Python language shows the value of the last expression in your code.
6th Mar 2017, 7:10 PM
Rohit Swami
Rohit Swami - avatar