本文介绍了Ruby-按哈希数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个哈希数组:
@fournisseurs = [
{ id: 10592,
nom: 'Carrossier Procolor Armand-Paris (Garage Michel Tondreau)',
distance: '3.9 km',
dispos: nil
},
{ id: 10463,
nom: 'Carrossier Procolor Grand Beauport(Garage Michel Tondreau)',
distance: '3.8 km',
dispos: nil
},
{ id: 10594,
nom: 'Honda Charlesbourg',
distance: '5.2 km',
dispos: nil
},
{ id: 10508,
nom: 'Carrossier ProColor Charlesbourg',
distance: '15.5 km',
dispos: nil
}]
我想按距离对它进行排序.我尝试了@fournisseurs.sort_by! { |fournisseur| fournisseur[:distance]}
,但是它没有对我的哈希数组进行排序.我读到sort_by!
不稳定.我该怎么办?
And I would like to sort it by distance. I tried @fournisseurs.sort_by! { |fournisseur| fournisseur[:distance]}
, but it doesn't sort my array of hashes. I read that sort_by!
was unstable. How can I do that?
提前谢谢!
推荐答案
假设每个距离都以字符串形式给出,则需要将其转换为浮点数以有效地按距离排序.
Assuming that each distance is given as a string, you need to convert it to a float to effectively sort by distance.
@fournisseurs = [
{ id: 10592,
nom: 'Carrossier Procolor Armand-Paris (Garage Michel Tondreau)',
distance: '3.9 km',
dispos: nil
},
{ id: 10463,
nom: 'Carrossier Procolor Grand Beauport(Garage Michel Tondreau)',
distance: '3.8 km',
dispos: nil
},
{ id: 10594,
nom: 'Honda Charlesbourg',
distance: '5.2 km',
dispos: nil
},
{ id: 10508,
nom: 'Carrossier ProColor Charlesbourg',
distance: '15.5 km',
dispos: nil
}]
@fournisseurs.sort_by! { |f| f[:distance].to_f}
puts @fournisseurs.inspect
这篇关于Ruby-按哈希数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!