Ruby - return true if any element in Array satisfies condition but false otherwise

Hi,

A Ruby question.

Anyone know a function that loops through an array and returns true if
any one element satisfies the condition but false if none satisfy the
condition? And it should do this in one line. Something like

any_bot_follower = followers.each {|f| return true if f.bot?}

The above returns an array if none of the Array elements satisfy the
condition. I want it to return false instead.

I have seen a function somewhere that does this but just not able to
nail it down. Hoping one of you here would know.

Thanks!

On 16 July 2010 13:48, Ram [email protected] wrote:

Anyone know a function that loops through an array and returns true if
any one element satisfies the condition but false if none satisfy the
condition? And it should do this in one line. Something like

You probably want “.detect”
http://ruby-doc.org/core/classes/Enumerable.html#M003123

any_bot_follower = followers.detect(false) { |f| f.bot? }

On 16 July 2010 13:51, Michael P. [email protected] wrote:

On 16 July 2010 13:48, Ram [email protected] wrote:

Anyone know a function that loops through an array and returns true if
any one element satisfies the condition but false if none satisfy the
condition? And it should do this in one line. Something like

You probably want “.detect”
http://ruby-doc.org/core/classes/Enumerable.html#M003123

any_bot_follower = followers.detect(false) { |f| f.bot? }

Or Enumerable#any?

http://apidock.com/ruby/Enumerable/any%3F

any_bot_follower = followers.any? { |f| f.bot? }

Cheers,

Andy

On 16 July 2010 14:19, Andy J. [email protected] wrote:

On 16 July 2010 13:51, Michael P. [email protected] wrote:

You probably want “.detect”

Or Enumerable#any?
http://apidock.com/ruby/Enumerable/any%3F
any_bot_follower = followers.any? { |f| f.bot? }

Even better! As it just returns true/false (what the OP asked for)

Goes to show what reading the manual can give you :smiley:

Perfect! :slight_smile: thanks! Couldn’t find docs on this though.

On Jul 16, 7:07 pm, Frederick C. [email protected]

On Jul 16, 1:48 pm, Ram [email protected] wrote:

Hi,

A Ruby question.

Anyone know a function that loops through an array and returns true if
any one element satisfies the condition but false if none satisfy the
condition? And it should do this in one line. Something like

any?

Fred

Array includes module Enumerable. ‘any?’ can be found in Enumerable.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs