In this example:
def hello
puts "hi"
end
def hello
"hi"
end
What's the difference between the first and second functions?
In Ruby functions, when a return value is not explicitly defined, a function will return the last statement it evaluates. If only a print statement is evaluated, the function will return nil.
Thus, the following prints the string hi and returns nil:
puts "hi"
In contrast, the following returns the string hi:
"hi"
Consider the following:
def print_string
print "bar"
end
def return_string
"qux" # same as `return "qux"`
end
foo = print_string
foo #=> nil
baz = return_string
baz #=> "qux"
Note, however, that you can print and return something out of the same function:
def return_and_print
print "printing"
"returning" # Same as `return "returning"`
end
The above will print the string printing, but return the string returning.
Remember that you can always explicitly define a return value:
def hello
print "Someone says hello" # Printed, but not returned
"Hi there!" # Evaluated, but not returned
return "Goodbye" # Explicitly returned
"Go away" # Not evaluated since function has already returned and exited
end
hello
#=> "Goodbye"
So, in sum, if you want to print something out of a function, say, to the console/log – use print. If you want to return that thing out of the function, don't just print it – ensure that it is returned, either explicitly or by default.
The first one uses the puts method to write "hi" out to the console and returns nil
the second one returns the string "hi" and doesn't print it
Here's an example in an irb session:
2.0.0p247 :001 > def hello
2.0.0p247 :002?> puts "hi"
2.0.0p247 :003?> end
=> nil
2.0.0p247 :004 > hello
hi
=> nil
2.0.0p247 :005 > def hello
2.0.0p247 :006?> "hi"
2.0.0p247 :007?> end
=> nil
2.0.0p247 :008 > hello
=> "hi"
2.0.0p247 :009 >