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
Post a Comment