Jak posortować tablicę skrótów według wartości w haśle?
Ten kod Ruby nie zachowuje się tak, jak oczekiwałem:
# 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
Chcę posortować tablicę skrótów według klucza "value" , ale są one drukowane nieposortowane.
100
Author: the Tin Man, 2010-07-01
4 answers
Ruby sort
nie sortuje na miejscu. (Masz może Tło Pythona?)
Ruby ma sort!
do sortowania in-place, ale nie ma wariantu in-place dla sort_by
. W praktyce można wykonać:
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/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-30 23:29:21
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-30 23:29:21
Zgodnie z @shteef, ale zaimplementowane z wariantem sort!
zgodnie z sugestią:
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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-18 17:01:20
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-18 17:01:20
Chociaż Ruby nie ma wariantu sort_by
in-place, możesz to zrobić:
sort_me = sort_me.sort_by { |k| k["value"] }
Array.sort_by!
dodano w 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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-18 17:01:07
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-18 17:01:07
Możesz użyć sort_me.sort_by!{ |k| k["value"]}
. To powinno zadziałać.
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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-13 16:30:19
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-13 16:30:19