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.
I would use:
[0, 0, 1, 0, 1, 1, 0].drop_while(&:zero?)
#=> [1, 0, 1, 1, 0]
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}
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