Topic: order hash by 2 atribut

salam,

i'm use Rails 2.

i have hash like this :

[#<Player last_name: "cacaca", grade_level: "1">,
 #<Player last_name: "aaaaaa", grade_level: "1">,
 #<Player last_name: "babu", grade_level: "2">,
 #<Player last_name: "player58", grade_level: "5">]

how can i sort this hash like this :

[#<Player last_name: "aaaaaa", grade_level: "1">,
 #<Player last_name: "cacaca", grade_level: "1">,
 #<Player last_name: "babu", grade_level: "2">,
 #<Player last_name: "player58", grade_level: "5">]

Last edited by sloth (2010-12-06 12:42:43)

Re: order hash by 2 atribut

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)

Re: order hash by 2 atribut

thank's for your reply

yup.. it work if just for one attribut.

but i want sort by "grade_level" and then sort by "last_name".

here's my current solution :
  player is an model for database.
  so i recall active record with condition sort by 'grade_level' and 'last_name'