2013-08-02 124 views
1

我有紅寶石關係類的在軌道上的數組,我稱之爲使用@relations如何按名稱屬性對數組類進行排序?

例子:

@relations[0] {id => 13, name => 'Giovanni', age => 50} 
@relations[1] {id => 25, name => 'Astolf', age => 27} 
@relations[2] {id => 5, name => 'Bob', age => 37} 

我要作爲排序依據的名稱數組。它會列出如下:

@relations[0] {id => 25, name => 'Astolf', age => 27} 
@relations[1] {id => 5, name => 'Bob', age => 37} 
@relations[2] {id => 13, name => 'Giovanni', age => 50} 

我該怎麼辦?

回答

6

很簡單:

@relations = [{:id => 13, :name => 'Giovanni', :age => 50}, 
       {:id => 25, :name => 'Astolf', :age => 27}, 
       {:id => 5, :name => 'Bob', :age => 37}] 

@relations.sort_by{|e| e[:name]} 
# => [{:id=>25, :name=>"Astolf", :age=>27}, 
#  {:id=>5, :name=>"Bob", :age=>37}, 
#  {:id=>13, :name=>"Giovanni", :age=>50}] 
+0

好吧,這真的是正確的。但是,如果名稱是由另一個函數獲得的?例如:@relations [0] .getname =>「Astolf」? – kamusett

+0

我在這個網站上找到:http://ariejan.net/2007/01/28/ruby-sort-an-array-of-objects-by-an-attribute/。謝謝。 – kamusett

相關問題