如何按名称属性对数组类进行排序?

时间:2013-08-02 18:58:20

标签: ruby-on-rails ruby sorting

我在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}

我该怎么做?

1 个答案:

答案 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}]