Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the first n elements from Ruby array that satisfy a predicate?

Tags:

ruby

I want to get all items from an array, which satisfy a predicate. Once I see an element that doesn't satisfy, I should stop iterating. For example:

[1, 4, -9, 3, 6].select_only_first { |x| x > 0}

I'm expecting to get: [1, 4]

like image 785
yegor256 Avatar asked Mar 19 '23 19:03

yegor256


1 Answers

This is how you want :

arup@linux-wzza:~> pry
[1] pry(main)> [1, 4, -9, 3, 6].take_while { |x| x > 0}
=> [1, 4]
[2] pry(main)>

Here is the documentation :

arup@linux-wzza:~> ri Array#take_while

= Array#take_while

(from ruby site)
------------------------------------------------------------------------------
  ary.take_while { |arr| block }  -> new_ary
  ary.take_while                  -> Enumerator

------------------------------------------------------------------------------

Passes elements to the block until the block returns nil or false, then stops
iterating and returns an array of all prior elements.

If no block is given, an Enumerator is returned instead.

See also Array#drop_while

  a = [1, 2, 3, 4, 5, 0]
  a.take_while { |i| i < 3 }  #=> [1, 2]


lines 1-20/20 (END)
like image 192
Arup Rakshit Avatar answered Apr 27 '23 10:04

Arup Rakshit