From: Vincent Manis Date: 2011-04-14T14:08:39+09:00 Subject: Re: Noob question re:returning nil On 2011-04-13, at 21:27, 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? If I'm not mistaken, you're doing something like this. irb(main):001:0> def myputs(x) irb(main):002:1> puts("**" + x + "**") irb(main):003:1> end => nil irb(main):004:0> myputs("foobar") **foobar** => nil The return value of myputs is the value of the last expression, which is whatever puts returns. If you do ri 'Kernel#puts', you will find that it always returns nil, which is what you're getting. That's a characteristic of Kernel#puts. The other piece to the puzzle is that irb displays the return value of whatever you enter. So calling myputs displays a message, and then shows the return value of nil. There may be a way of turning off the display of returned values in irb. If so, I don't know what it is, because I've never wanted to use it. Maybe someone else can tell you that. The important point is that displaying the returned value is only a characteristic of irb. Running a program via the ruby command doesn't display return values, and therefore you only get printed that which you explicitly specify is to be printed, via puts or print or some such. Hope that helps -- vincent