-1

I've tried for several hours making this work.

i have this code where i have around 20 different persons, with different ages and names.

how can i make ruby searching through all the ages and show the highest age as and integer

i've been searching a lot, but cant seem to make it work. i've even tried to make it sort the numbers and the print the last age, which must be the highest number

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

Best regards

Stefan
  • 109,145
  • 14
  • 143
  • 218
Frederik
  • 51
  • 1
  • 1
  • 7
  • 1
    You need to show more of your code, including where/how all the persons are defined. Also, use the formatting mechanism for code blocks (see help). – Peter Alfvin Oct 07 '13 at 14:25

4 Answers4

3

If you have a class like this:

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

And an array like this:

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

Finding the maximum age

You can get the ages with Array#map:

people.map { |person| person.age }
#=> [10, 20, 30]

# or shorter

people.map(&:age)
#=> [10, 20, 30]

And the maximum value with Enumerable#max:

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

Finding the oldest person

Or you could find the oldest person with 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 his or her age with:

oldest.age
#=> 30
Stefan
  • 109,145
  • 14
  • 143
  • 218
0

Say for example your class looks like this:

class Person
  attr_reader :firstname, :familyname, :age

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

And say that you have an array of these objects called people. Then you could do something like:

puts people.max_by { |p| p.age }.age
Alex D
  • 29,755
  • 7
  • 80
  • 126
0

Use max

e.g

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

a,b,c,d = C.new(10), C.new(2), C.new(22), C.new(15)

[a,b,c,d].map(&:age).max #=> 22   
[a.age,b.age,c.age,d.age].max #=> 22
Bala
  • 11,068
  • 19
  • 67
  • 120
0

Once you've collected all the instances into an array, using one of the techniques shown in How to get class instances in Ruby?, you can use the technique shown in Finding the element of a Ruby array with the maximum value for a particular attribute to find the maximum age. For example, if Foo is your class and age is an attribute of your class, the following should work:

ObjectSpace.each_object.select{|foo| obj.class == Foo}.max_by {|foo| foo.age}
Community
  • 1
  • 1
Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106