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 !

7
  • I am tempted to close it as a duplicate Commented Jun 5, 2018 at 13:24
  • 1
    Possible duplicate of How to sort an array of hashes in ruby Commented Jun 5, 2018 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... Commented Jun 5, 2018 at 13:32
  • 1
    @Stefan I don't get a error message, but it doesn't sort my array of hashes. Commented Jun 5, 2018 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. Commented Jun 5, 2018 at 13:33

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

You don't have to splitto_f ignores tailing characters, i.e. '3.9 km'.to_f returns 3.9.
@Stefan, fixed.
"@Stefan, fixed. – Stefan" – that has a nice schizophrenic touch 🙃

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.