6

Given an array like:

[1, 2, nil, nil, 3, nil, 4, 5, 6, nil, nil, nil]

id like to remove the nil's from the end of the array. Not hard to solve with some ugly loops, but I was hoping there was a Ruby way to do it.

Result: [1, 2, nil, nil, 3, nil, 4, 5, 6]
0

5 Answers 5

22

How about this:

a.pop until a.last
Sign up to request clarification or add additional context in comments.

6 Comments

Smart. Mayby too smart but +1 anyway.
No you're not, it will only pop nils (and falses)
Hmm, I didn't expect this to be the accepted answer. I actually agree with @steenslag. Maybe better or more realistic is: a.pop until a.empty? or a.last
Or better a.pop while a.last.nil? to avoid losing all trailing false's.
stumbled across this, small bug, you will get infinite loop if all the values are nil, need to add a size condition: a.pop while a.last.nil? && a.size>0
|
8

Not sure why you would want the nil in between, but I digress!

array = [1, 2, nil, nil, 3, nil, 4, 5, 6, nil, nil, nil]
array.reverse.drop_while {|i| i == nil}.reverse

2 Comments

This is great. Didn't know about drop_while! Thank you.
Nice answer, thank you. As to why you would want the middle nils - in my case, I have imported a CSV file which contains column headings - and also some 'white space' columns on the end of each line. The nils in the middle represent 'the user didn't include a value', whereas the trailing ones represent 'the spreadsheet export included dud columns'.
3
foo = [1, 2, nil, nil, 3, nil, 4, 5, 6, nil, nil, nil]
foo.reverse.drop_while(&:nil?).reverse
# [1, 2, nil, nil, 3, nil, 4, 5, 6] 

Comments

2

Here's a one-liner for you :)

a =  [1, 2, nil, nil, 3, nil, 4, 5, 6, nil, nil, nil] 

a[0..a.rindex{|el| !el.nil?}] # => [1, 2, nil, nil, 3, nil, 4, 5, 6]

Comments

0
while(!(a = ar.pop)){}; ar.push a 

Still an ugly loop, but maybe less ugly?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.