Remove null elements from end of array in Ruby

Given an array like:

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

id wanted to remove nil from the end of the array. It's not hard to solve some ugly loops, but I was hoping this would be a Ruby way.

 Result: [1, 2, nil, nil, 3, nil, 4, 5, 6] 
+4
source share
5 answers

How about this:

 a.pop until a.last 
+17
source

Not sure why you need zero, but I'm distracted!

 array = [1, 2, nil, nil, 3, nil, 4, 5, 6, nil, nil, nil] array.reverse.drop_while {|i| i == nil}.reverse 
+7
source
 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] 
+3
source

Here is 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] 
+2
source
 while(!(a = ar.pop)){}; ar.push a 

Still an ugly loop, but maybe less ugly?

0
source

Source: https://habr.com/ru/post/1444212/


All Articles