array = [{ name:'Joe', class:'foo' },
{ name:'Bob', class:'bar' },
{ name:'Hal', class:'baz' },
{ name:'Kim', class:'qux' },
{ name:'Zoe', class:'bar' }
]
按以下顺序按类排序的好方法是什么:qux、bar、foo、baz?
array = [{ name:'Joe', class:'foo' },
{ name:'Bob', class:'bar' },
{ name:'Hal', class:'baz' },
{ name:'Kim', class:'qux' },
{ name:'Zoe', class:'bar' }
]
按以下顺序按类排序的好方法是什么:qux、bar、foo、baz?
像这样,例如:
array = [{ name:'Joe', class:'foo' },
{ name:'Bob', class:'bar' },
{ name:'Hal', class:'baz' },
{ name:'Kim', class:'qux' },
{ name:'Zoe', class:'bar' }
]
order = %w[qux bar foo baz]
sorted = array.sort_by{|el| order.index(el[:class])}
sorted # => [{:name=>"Kim", :class=>"qux"},
# {:name=>"Bob", :class=>"bar"},
# {:name=>"Zoe", :class=>"bar"},
# {:name=>"Joe", :class=>"foo"},
# {:name=>"Hal", :class=>"baz"}]
order = %w[qux bar foo baz]
array.sort_by{|h| order.index(h[:class])}
给出:
[
{
:name => "Kim",
:class => "qux"
},
{
:name => "Bob",
:class => "bar"
},
{
:name => "Zoe",
:class => "bar"
},
{
:name => "Joe",
:class => "foo"
},
{
:name => "Hal",
:class => "baz"
}
]