Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a ruby idiom for popping items from an array while a condition is true

Tags:

ruby

Is there a Ruby idiom for popping items from an array while a condition is true, and returning the collection?

I.e,

# Would pop all negative numbers from the end of 'array' and place them into 'result'.
result = array.pop {|i| i < 0} 

From what I can tell, something like the above doesn't exist.

I'm currently using

result = []
while array.last < 0 do
  result << array.pop
end
like image 783
Lilith River Avatar asked Mar 14 '13 16:03

Lilith River


People also ask

How do you print an array element in Ruby?

Ruby printing array contentsThe array as a parameter to the puts or print method is the simplest way to print the contents of the array. Each element is printed on a separate line. Using the inspect method, the output is more readable. The line prints the string representation of the array to the terminal.

How do you delete an element from an array in Ruby?

Ruby | Array delete() operation Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array. delete() Parameter: obj - specific element to delete Return: last deleted values from the array.


2 Answers

Maybe you are looking for take_while?

array = [-1, -2, 0, 34, 42, -8, -4]
result = array.reverse.take_while { |x| x < 0 }

result would be [-8, -4].

To get the original result back you could use drop_while instead.

result = array.reverse.drop_while { |x| x < 0 }.reverse

result would be [-1, -2, 0, 34, 42] in this case.

like image 174
squiguy Avatar answered Sep 30 '22 14:09

squiguy


You could write it yourself:

class Array
  def pop_while(&block)
    result = []
    while not self.empty? and yield(self.last)
      result << self.pop
    end
    return result
  end
end

result = array.pop_while { |i| i < 0 }
like image 30
Huluk Avatar answered Sep 30 '22 15:09

Huluk