Ruby way to find in an Array the object with a maximun in an attribute?

Hi, I’ve an Array of objects containing some attributes:

class SRV

  • @priority
  • @domain
  • @port
    end

In the Array I have 3 SRV objects:

Array[0]

Array[1]

Array[2]

And I need to get an array containing the Array elements with smallest
@priority value, this is:

ResultArray[0]

ResultArray[1]

Which is the best way to get the final array? Thanks for any suggestion.

El Viernes, 27 de Junio de 2008, Iñaki Baz C. escribió:

Which is the best way to get the final array? Thanks for any suggestion.

Done :slight_smile:

Array.sort! { |a,b| (a.priority <=> b.priority) }

Iñaki Baz C. wrote:

El Viernes, 27 de Junio de 2008, Iñaki Baz C. escribió:

Which is the best way to get the final array? Thanks for any suggestion.

Done :slight_smile:

Array.sort! { |a,b| (a.priority <=> b.priority) }

Yes! “sort_by” is nice too. My code just gives the minima (using a
struct, it should work with a class)

#preparation
Somestruct = Struct.new(:priority,:domain,:port)
ar = []
5.times do
ar << Somestruct.new(rand(10),rand(10),rand(10))
end
puts ar

#let’s go
smallest = ar.min{|x,y,|x.priority<=>y.priority}
minima = ar.select{ |element| element.priority==smallest.priority }

in ruby 1.9 the last 2 lines can be replaced (i think) by

minima = ar.min_by{|x|x.priority}

puts “only minimal priority’s:”
puts minima