Ordering a hash in descending order in Ruby doesn't work -
i have hash contains commit id (key) , number (value). in following how added value hash:
@allcommits[commit] = count
the following example commit ids , values:
key: 42ac06787b8db8a6a299aa65482072f238dffc21 value: 3 key: a2658427039df49687d5ea590d8a0053631a2571 value: 1 key: 4ab0aab2e5fe9d650ce1fb96c48587783c7e296c value: 1 key: 469a15d2ecea8671a3f3c77813011163e2605d9e value: 4 key: 66558be4e7ddd5e9d9db3d512c859410d275c97a value: 1 key: ee9b9bac044c8306c81c7b3a3aa0632a7835e913 value: 2
then, before printing want order hash in descending order based on value. so, did
@allcommits.sort_by {|k,v| v}.reverse
but did't work, gave me order insert them in hash.
i also, tried
hash[@allcommits.sort_by{|k, v| v}.reverse]
but nothing.
i can't see problem here, help?
it seems working me:
input:
@all_commits = { '42ac06787b8db8a6a299aa65482072f238dffc21' => 3, 'a2658427039df49687d5ea590d8a0053631a2571' => 1, '4ab0aab2e5fe9d650ce1fb96c48587783c7e296c' => 1, '469a15d2ecea8671a3f3c77813011163e2605d9e' => 4, '66558be4e7ddd5e9d9db3d512c859410d275c97a' => 1, 'ee9b9bac044c8306c81c7b3a3aa0632a7835e913' => 2 } puts "sorted" @all_commits.sort_by {|k,v| v}.reverse.each{|x| p x} puts puts "unsorted" @all_commits.each{|x| p x}
output:
sorted ["469a15d2ecea8671a3f3c77813011163e2605d9e", 4] ["42ac06787b8db8a6a299aa65482072f238dffc21", 3] ["ee9b9bac044c8306c81c7b3a3aa0632a7835e913", 2] ["4ab0aab2e5fe9d650ce1fb96c48587783c7e296c", 1] ["a2658427039df49687d5ea590d8a0053631a2571", 1] ["66558be4e7ddd5e9d9db3d512c859410d275c97a", 1] unsorted ["42ac06787b8db8a6a299aa65482072f238dffc21", 3] ["a2658427039df49687d5ea590d8a0053631a2571", 1] ["4ab0aab2e5fe9d650ce1fb96c48587783c7e296c", 1] ["469a15d2ecea8671a3f3c77813011163e2605d9e", 4] ["66558be4e7ddd5e9d9db3d512c859410d275c97a", 1] ["ee9b9bac044c8306c81c7b3a3aa0632a7835e913", 2]
my guess perform sort_by
not capture results. in ruby, many methods return new objects, , not update original hash. if have hash, call sort_by
on it, on separate line try print hash again, you'll see original hash because wasn't updated. instead have use return value of sort_by
call.
Comments
Post a Comment