Return First Value that Passes

Hello Everyone,
I am new to Ruby, but I like how many of the functions one would use
in programming are baked right in. Here is my problem, I have an array
with objects that is ordered by a particular attribute, lets call it
“age”.

What I seek to do is to iterate through the array, and return the object
that passes a certain test function. Lets say the first object with an
age greater than 35. Is there a function that will already do this, or
do I have to roll my own ?

Any help is greatly appreciated.

On Sat, Feb 11, 2012 at 11:25 AM, Jonah J. [email protected]
wrote:

that passes a certain test function. Lets say the first object with an
age greater than 35. Is there a function that will already do this, or

ri detect

http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-find

Always try the docs :slight_smile:

– Matma R.

On Fri, Feb 10, 2012 at 9:25 PM, Jonah J.
[email protected]wrote:

Any help is greatly appreciated.


Posted via http://www.ruby-forum.com/.

You look these kinds of methods up in the Enumerable class
http://rubydoc.info/stdlib/core/1.9.3/Enumerable In your case,
find/detect

User = Struct.new :name, :age
users = [
User.new(“Phil”, 33),
User.new(“Sandy”, 25),
User.new(“Carl”, 43),
User.new(“Jim”, 19)
]

users.find { |user| user.age > 35 } # => #<struct User name=“Carl”,
age=43>