我在rails上的ruby上有一个Relation类数组,我使用@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}
我该怎么做?
答案 0 :(得分: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}]