Forum: Ruby Array prepending nil object

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Serdar Kılıç (Guest)
on 2006-01-31 07:55
(Received via mailing list)
I'm going through Brian Schröder's tutorial and hit a small snag. The
code is (on page 16):

print 'Array as stack: '
stack = Array.new()
stack.push('a')
stack.push('b')
stack.push('c')
print stack.pop until stack.empty?

The display that I'm getting is:
Array as stack: cbanil

So somehow nil is creeping it's way into my array but I'm not sure
how. Any ideas?
Joel VanderWerf (Guest)
on 2006-01-31 08:14
(Received via mailing list)
Serdar Kılıç wrote:
> The display that I'm getting is:
> Array as stack: cbanil
>
> So somehow nil is creeping it's way into my array but I'm not sure
> how. Any ideas?

The nil is just the return value of the last expression, not part of the
output of the print calls.

You can see it more clearly in irb:

irb(main):001:0> print 'Array as stack: '
Array as stack: => nil
irb(main):002:0> stack = Array.new()
=> []
irb(main):003:0> stack.push('a')
=> ["a"]
irb(main):004:0> stack.push('b')
=> ["a", "b"]
irb(main):005:0> stack.push('c')
=> ["a", "b", "c"]
irb(main):006:0> print stack.pop until stack.empty?
cba=> nil

The printed output shows up on the left of the =>.
Brian Caswell (Guest)
on 2006-01-31 08:20
(Received via mailing list)
On Jan 31, 2006, at 12:54 AM, Serdar Kõlõ wrote:
> So somehow nil is creeping it's way into my array but I'm not sure
> how. Any ideas?

You are running this inside irb.  print returns nil, which you are
interpreting as being part of the output.

Try adding:

	print "\n"

To the bottom of your example.

Brian
Serdar Kılıç (Guest)
on 2006-01-31 08:26
(Received via mailing list)
Thanks Joel. I did actually use irb but only through MINGW on Windows
XP, where unfortunately you don't get the descriptive "code/line
marker" thingys.
Serdar Kılıç (Guest)
on 2006-01-31 08:29
(Received via mailing list)
Thank you too Brian, that makes it quite clear.
This topic is locked and can not be replied to.