Reputation: 671
Edited to better state the question:
I am writing a method to convert a number into a string in english. For example: 888 would be converted to "eight hundred and eighty eight".
Which of both options should I use and why?
Option A (using "puts" inside function):
def convert_number_to_english number
<code>
puts number_in_english
end
convert_number_to_english 888
Option B (using "return" inside function and later using "puts" before calling function):
def convert_number_to_english number
<code>
return number_in_english
end
puts convert_number_to_english 888
Upvotes: 0
Views: 2290
Reputation: 10041
Generally speaking, I try to keep my code 'pure'. By 'pure', I mean no additional side effects.
In this specific case your function, based on its name, is asking for a number and returning an english readable string representation of the given number. I would avoid doing any IO (puts
, File.open
, etc, which are considered side effects) within this function. I would go with the return
variation.
If your function had been called something like print_converted_number
, I would say that it would be okay to have puts
instead of return
.
Basically what I am saying is that you should name your functions with what they actually do.
Note: In Ruby, you can generally leave out the return
from most functions. In Ruby, a function will automatically return the last thing evaluated.
Upvotes: 3