It looks like an Array of Player objects and not like a Hash.
Any way, you can use 'sort' or 'sort_by' method
enum.sort => array
enum.sort {| a, b | block } => array
Returns an array containing the items in enum sorted, either according to their own <=> method, or by using the results of the supplied block. The block should return -1, 0, or +1 depending on the comparison between a and b. As of Ruby 1.8, the method Enumerable#sort_by implements a built-in Schwartzian Transform, useful when key computation or comparison is expensive..
%w(rhea kea flea).sort #=> ["flea", "kea", "rhea"]
(1..10).sort {|a,b| b <=> a} #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
see http://ruby-doc.org/ruby-1.9/index.html for more details.
Imagine that you have a Player class defined like that:
class Player
attr_accessor :name
def initialize(name)
@name=name
end
end
arr = Array.new
p = Player.new('mark')
arr << p
p = Player.new('john')
arr << p
p = Player.new('zozo')
arr << p
puts "before sorting #{arr.inspect}"
new_arr = arr.sort {|a, b| a.name <=> b.name}
puts "after sorting #{new_arr.inspect}"
and the output will be:
before sorting [#<Player:0xb78351f0 @name="mark">, #<Player:0xb78351c8 @name="john">, #<Player:0xb78351a0 @name="zozo">]
after sorting [#<Player:0xb78351c8 @name="john">, #<Player:0xb78351f0 @name="mark">, #<Player:0xb78351a0 @name="zozo">]
It's just an example to give you an idea how it works.
Last edited by Javix (2010-12-06 17:01:31)