yegor256
yegor256

Reputation: 105210

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

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]

Upvotes: 4

Views: 1830

Answers (3)

Adrian
Adrian

Reputation: 425

If you're exploring other solution, this works too:

[1, 4, -9, 3, 6].slice_before { |x| x <= 0}.to_a[0]

You have to change x > 0 to x <=0.

Upvotes: 1

Darkmouse
Darkmouse

Reputation: 1939

That was an excellent answer Arup. My method is slightly more complicated.

numbers = [1,4,-9,3,6]

i = 0
new_numbers = []
until numbers[i] < 0
  new_numbers.push(numbers[i])
  i+= 1
end

=> [1,4]

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118299

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)

Upvotes: 6

Related Questions