On Thu, Apr 14, 2011 at 01:27:48PM +0900, Nathan McDorman wrote:
Hello all, I am a beginner programmer and a beginner to Ruby. I was just
going through a tutorial book and trying to create some programs. The
current program I am working on I am having trouble with.
I have defined a method and the last thing in the method is a puts
concatenation. The program runs and does everything correctly except for
when I call the method it puts the string and then nil underneath.
I thought the return value was the last value of the string so I don’t
understand why it is doing this. How do I get rid of the nil?
nil. If you want to have a
puts in the
method, then return the value of the string, you’ll have to do something
to return the value of the string explicitly after the
For instance, this will return
puts 'one' + ' ' + 'two'
This will return
puts (bar = 'one' + ' ' + 'two')
On the other hand, you’re probably better off saving your
puts for the
output of the method, unless the
puts is the only reason to have the
method. For instance, this:
foo + ' ' + bar
puts combined = concat('one','two')
. . . is probably better than this:
puts combined_val = foo + ' ' + bar
combined = concat('one', 'two')
The reason it’s probably better is that the second example does things
inside the method that is not actually part of the core reason for the
method, and you actually save complexity by handling the output method
puts outside of the method.
I hope that helps.