Array prepending nil object

S

Serdar Kýlýç

I'm going through Brian Schr=F6der's tutorial and hit a small snag. The
code is (on page 16):

print 'Array as stack: '
stack =3D 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?
 
J

Joel VanderWerf

Serdar said:
I'm going through Brian Schr=C3=B6der's tutorial and hit a small snag. = The
code is (on page 16):
=20
print 'Array as stack: '
stack =3D Array.new()
stack.push('a')
stack.push('b')
stack.push('c')
print stack.pop until stack.empty?
=20
The display that I'm getting is:
Array as stack: cbanil
=20
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: =3D> nil
irb(main):002:0> stack =3D Array.new()
=3D> []
irb(main):003:0> stack.push('a')
=3D> ["a"]
irb(main):004:0> stack.push('b')
=3D> ["a", "b"]
irb(main):005:0> stack.push('c')
=3D> ["a", "b", "c"]
irb(main):006:0> print stack.pop until stack.empty?
cba=3D> nil

The printed output shows up on the left of the =3D>.

--=20
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407
 
B

Brian Caswell

print 'Array as stack: '
stack =3D 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?

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

Try adding:

print "\n"

To the bottom of your example.

Brian=
 
S

Serdar Kýlýç

Thank you too Brian, that makes it quite clear.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top