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

  • Thread starter Iñaki Baz Castillo
  • Start date
I

Iñaki Baz Castillo

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

class SRV
=2D @priority
=2D @domain
=2D @port
end

In the Array I have 3 SRV objects:

Array[0]
=2D @priority =3D 1
=2D @domain =3D mydomain.com
=2D @port =3D 5060

Array[1]
=2D @priority =3D 0
=2D @domain =3D mydomain2.net
=2D @port =3D 5060

Array[2]
=2D @priority =3D 0
=2D @domain =3D mydomain3.org
=2D @port =3D 5070


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

ResultArray[0]
=2D @priority =3D 0
=2D @domain =3D mydomain2.net
=2D @port =3D 5060

ResultArray[1]
=2D @priority =3D 0
=2D @domain =3D mydomain3.org
=2D @port =3D 5070


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




=2D-=20
I=C3=B1aki Baz Castillo
 
I

Iñaki Baz Castillo

El Viernes, 27 de Junio de 2008, I=C3=B1aki Baz Castillo escribi=C3=B3:
And I need to get an array containing the Array elements with smallest
@priority value, this is:

ResultArray[0]
- @priority =3D 0
- @domain =3D mydomain2.net
- @port =3D 5060

ResultArray[1]
- @priority =3D 0
- @domain =3D mydomain3.org
- @port =3D 5070


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

Done :)

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

=2D-=20
I=C3=B1aki Baz Castillo
 
S

Siep Korteling

Iñaki Baz Castillo said:
El Viernes, 27 de Junio de 2008, Iñaki Baz Castillo escribió:

Done :)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top