Removing "nil" entries from array

T

Thomas Adam

Dear All,

I have a really weird situation. I'm reading a file into an array, based
on a grep match. This works fine.....

...yet I re-ran my program using the same data file (unchanged) and now my
array is being intermittently populated with "nil" values. Using "uniq()"
doesn't remove them. Any ideas?

-- Thomas Adam

=====
Thomas Adam

"The Linux Weekend Mechanic" -- www.linuxgazette.com

________________________________________________________________________
Want to chat instantly with your online friends? Get the FREE Yahoo!
Messenger http://mail.messenger.yahoo.co.uk
 
J

Joey Gibson

...yet I re-ran my program using the same data file (unchanged) and now my
array is being intermittently populated with "nil" values. Using "uniq()"
doesn't remove them. Any ideas?

What about using delete_if?

a = [:foo, nil, :bar, :baz, nil, nil, "testing"]
a.delete_if {|x| x == nil}
=> [:foo, :bar, :baz, "testing"]

delete_if modifies the array in place. If you want non-destuctive, use
"reject" instead.
 
M

Michael Garriss

Thomas said:
Dear All,

I have a really weird situation. I'm reading a file into an array, based
on a grep match. This works fine.....

...yet I re-ran my program using the same data file (unchanged) and now my
array is being intermittently populated with "nil" values. Using "uniq()"
doesn't remove them. Any ideas?

[1, nil, 2, nil, 3, nil, 4].compact!
--> [1, 2, 3, 4]

....or you could use #compact if you don't want to change the array in
place.

Regards,
Michael
 
J

Jason Creighton

Dear All,

I have a really weird situation. I'm reading a file into an array, based
on a grep match. This works fine.....

..yet I re-ran my program using the same data file (unchanged) and now my
array is being intermittently populated with "nil" values. Using "uniq()"
doesn't remove them. Any ideas?

Well, as several people have mentioned, you could use Array#compact, but
if I were you, I would try to find out why you're getting nil values.
Could you post the smallest possible code snippet + data that shows this
problem?

Jason Creighton
 

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,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top