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.

···

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

ri detect

···

On Sat, Feb 11, 2012 at 11:25 AM, Jonah Jameson <justindallas@gmail.com> 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

You look these kinds of methods up in the Enumerable class
Module: Enumerable — Documentation for core (1.9.3) 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>

···

On Fri, Feb 10, 2012 at 9:25 PM, Jonah Jameson <justindallas@gmail.com>wrote:

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.

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

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

Always try the docs :slight_smile:

-- Matma Rex