Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove nil items from end of array in Ruby

Tags:

ruby

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]
like image 937
Adam Gotterer Avatar asked Nov 05 '12 21:11

Adam Gotterer


3 Answers

How about this:

a.pop until a.last
like image 186
pguardiario Avatar answered Sep 30 '22 17:09

pguardiario


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
like image 27
omarvelous Avatar answered Sep 30 '22 17:09

omarvelous


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] 
like image 35
Kyle Avatar answered Sep 30 '22 17:09

Kyle