1

我在rails上的ruby上有一个关系类数组,我称之为使用@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}

我该怎么做?

4

1 回答 1

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}]
于 2013-08-02T18:59:47.127 回答