Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zero elements from array in Ruby

Tags:

ruby

I have an array like this:

a = [0, 0, 1, 0, 1, 1, 0]

I would like to remove the leading 0 elements to get this:

a = [1, 0, 1, 1, 0]

What's the best way to do this in Ruby? I have come up with a solution, but it doesn't feel as elegant as it could be:

count = 0
a.each do |element|
  break if element != 0
  count += 1
end
a = a[count..-1]

I feel like there might be a clean one-liner for this.

like image 904
inersha Avatar asked Dec 18 '22 13:12

inersha


2 Answers

I would use:

 [0, 0, 1, 0, 1, 1, 0].drop_while(&:zero?)
 #=> [1, 0, 1, 1, 0]
like image 88
spickermann Avatar answered Jan 04 '23 23:01

spickermann


You are looking for drop_while.

https://ruby-doc.org/core-2.6.3/Enumerable.html#method-i-drop_while

a = a.drop_while {|x| x == 0}
like image 23
matt Avatar answered Jan 04 '23 23:01

matt