¿Cómo ordeno una matriz de hashes por un valor en el hash?


Este código Ruby no se comporta como yo esperaría:

# create an array of hashes
sort_me = []
sort_me.push({"value"=>1, "name"=>"a"})
sort_me.push({"value"=>3, "name"=>"c"})
sort_me.push({"value"=>2, "name"=>"b"})

# sort
sort_me.sort_by { |k| k["value"]}

# same order as above!
puts sort_me

Estoy buscando ordenar la matriz de hashes por la clave "valor", pero se imprimen sin clasificar.

Author: the Tin Man, 2010-07-01

4 answers

Ruby sort no ordena en su lugar. (¿ Tiene antecedentes de Python, tal vez?)

Ruby tiene sort! para ordenar en el lugar, pero no hay ninguna variante en el lugar para sort_by. En la práctica, usted puede hacer:

sorted = sort_me.sort_by { |k| k["value"] }
puts sorted
 181
Author: Stéphan Kochen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-30 23:29:21

Según @shteef pero implementado con la variante sort! como se sugiere:

sort_me.sort! { |x, y| x["value"] <=> y["value"] }
 19
Author: bjg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-18 17:01:20

Aunque Ruby no tiene una variante in-place sort_by, puedes hacer:

sort_me = sort_me.sort_by { |k| k["value"] }

Array.sort_by! se añadió en 1.9.2

 6
Author: AG_,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-18 17:01:07

Puede usar sort_me.sort_by!{ |k| k["value"]}. Esto debería funcionar.

 2
Author: Mukesh Kumar Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-13 16:30:19