1

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 !

Simple Lime
  • 10,790
  • 2
  • 17
  • 32
  • I am tempted to [close it as a duplicate](https://stackoverflow.com/questions/5483889/how-to-sort-an-array-of-hashes-in-ruby) – Andrey Deineko Jun 05 '18 at 13:24
  • 1
    Possible duplicate of [How to sort an array of hashes in ruby](https://stackoverflow.com/questions/5483889/how-to-sort-an-array-of-hashes-in-ruby) – Joseph Cho Jun 05 '18 at 13:26
  • @JosephCho I checked this post, and it didn't help me cause I did the same and it doesn't sort my array of hashes... – Noémie Harvey Jun 05 '18 at 13:32
  • 1
    @Stefan I don't get a error message, but it doesn't sort my array of hashes. – Noémie Harvey Jun 05 '18 at 13:33
  • @NoémieHarvey thanks for the edit and the clarification. Unfortunately, that hash is invalid and would result in a `SyntaxError`. For example, it should be `:id => ...` or `"id" => ...` – same for the values. Without a working hash, it's unclear what's causing the problem. – Stefan Jun 05 '18 at 13:33
  • Copy and paste just one of your hashes into `irb`, I got lots of informative errors when I did so. Your hash definitions aren't valid. – pjs Jun 05 '18 at 13:39
  • "unstable" does not mean it doesn't work - it means that when 2 distances happen to be the same, then the order of the 2 is not guaranteed to be maintained. – steenslag Jun 05 '18 at 16:24

1 Answers1

6

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
Stefan
  • 109,145
  • 14
  • 143
  • 218
Stefan
  • 2,961
  • 1
  • 22
  • 34