From: Chad Perrin Date: 2011-04-14T14:15:11+09:00 Subject: Re: Noob question re:returning nil --yEPQxsgoJgBvi8ip Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable 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. >=20 > 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. >=20 > 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? 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 =3D '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 =3D concat('one','two') =2E . . is probably better than this: def concat(foo,bar) puts combined_val =3D foo + ' ' + bar combined_val end combined =3D 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. --=20 Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ] --yEPQxsgoJgBvi8ip Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.14 (FreeBSD) iEYEARECAAYFAk2mf9IACgkQ9mn/Pj01uKWzwACgwjtA/LnAJb4e2HBOuRcvX0VY qwQAoL449Ap/MqdqCQ7Hwk66hBcj5XHs =s1wL -----END PGP SIGNATURE----- --yEPQxsgoJgBvi8ip--