Evaluating `puts` returns `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 `puts` expression.
For instance, this will return `nil`:
def foo
puts 'one' + ' ' + 'two'
end
This will return `'one two'`:
def foo
puts (bar = 'one' + ' ' + 'two')
bar
end
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:
def concat(foo,bar)
foo + ' ' + bar
end
puts combined = concat('one','two')
. . . is probably better than this:
def concat(foo,bar)
puts combined_val = foo + ' ' + bar
combined_val
end
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.
···
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?
--
Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ]