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]
- @priority = 1
- @domain = mydomain.com
- @port = 5060
Array[1]
- @priority = 0
- @domain = mydomain2.net
- @port = 5060
Array[2]
- @priority = 0
- @domain = mydomain3.org
- @port = 5070
And I need to get an array containing the Array elements with smallest
@priority value, this is:
ResultArray[0]
- @priority = 0
- @domain = mydomain2.net
- @port = 5060
ResultArray[1]
- @priority = 0
- @domain = mydomain3.org
- @port = 5070
Which is the best way to get the final array? Thanks for any suggestion.
···
--
Iñaki Baz Castillo
Done 
Array.sort! { |a,b| (a.priority <=> b.priority) }
···
El Viernes, 27 de Junio de 2008, Iñaki Baz Castillo escribió:
And I need to get an array containing the Array elements with smallest
@priority value, this is:
ResultArray[0]
- @priority = 0
- @domain = mydomain2.net
- @port = 5060
ResultArray[1]
- @priority = 0
- @domain = mydomain3.org
- @port = 5070
Which is the best way to get the final array? Thanks for any suggestion.
--
Iñaki Baz Castillo
Iñaki Baz Castillo wrote:
- @domain = mydomain3.org
- @port = 5070
Which is the best way to get the final array? Thanks for any suggestion.
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
···
El Viernes, 27 de Junio de 2008, Iñaki Baz Castillo escribió:
--
Posted via http://www.ruby-forum.com/\.