ruby - How does `Hash#sort{|a, b| block}` work? -


in ruby-doc see example:

h = { "a" => 20, "b" => 30, "c" => 10  } h.sort {|a,b| a[1]<=>b[1]}   #=> [["c", 10], ["a", 20], ["b", 30]] 

can explain a[1]<=>b[1] means? comparing here? a key , b value? why comparing index 1?

a , b both arrays of [key, value] come hash#sort.

converts hsh nested array of [ key, value ] arrays , sorts it, using array#sort.

so a[1]<=>b[1] sorts resulting pairs value. if a[0]<=>b[0] sorting key.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -