Search code examples
rubyenumerable

ruby comparing groups of objects on a specific property


Possible Duplicate:
More concise version of max/min without the block

If I had N number of objects with specific attributes (in this example height), what is a good way to find the max or min?

 class Person
   attr_accessor: height
 end

 a = Person.new
 a.height = 10
 b = Person.new
 b.height = 11
 c = Person.new
 c.height = 12

 #what's a nice way to get the tallest person

Solution

  • To expand the answer here:

    class Person
      attr_accessor :height
    
      def initialize(height)
        self.height = height
      end
    end
    
    people = [ Person.new(10), Person.new(20), Person.new(30) ]
    
    tallest_person = people.max_by &:height