Ruby - Sort by array of hashes

2019-08-07 03:54发布

问题:

I have this array of hashes:

@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
}]

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?

Thanks in advance !

回答1:

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