arrays - Find max value in a class in ruby -


i've tried several hours making work.

i have code have around 20 different persons, different ages , names.

how can make ruby searching through ages , show highest age , integer

i've been searching lot, cant seem make work. i've tried make sort numbers , print last age, must highest number

def initialize(firstname, familyname, age)   @firstname = firstname   @familyname = familyname   @age = age 

best regards

if have class this:

class person   attr_accessor :age   def initialize(age)     @age = age   end end 

and array this:

people = [person.new(10), person.new(20), person.new(30)] 

finding maximum age

you can ages array#map:

people.map { |person| person.age } #=> [10, 20, 30]  # or shorter  people.map(&:age) #=> [10, 20, 30] 

and maximum value enumerable#max:

people.map(&:age).max #=> 30 

finding oldest person

or find oldest person enumerable#max_by:

oldest = people.max_by { |person| person.age } #=> #<person:0x007fef4991d0a8 @age=30>  # or shorter  oldest = people.max_by(&:age) #=> #<person:0x007fef4991d0a8 @age=30> 

and or age with:

oldest.age #=> 30 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

iphone - Three second countdown in cocos2d -

java.util.scanner - How to read and add only numbers to array from a text file -