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]
How about this:
a.pop until a.last
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With