Sort hash by key, return hash in Ruby

前端 未结 10 1456
时光取名叫无心
时光取名叫无心 2020-11-27 10:05

Would this be the best way to sort a hash and return Hash object (instead of Array):

h = {\"a\"=>1, \"c\"=>3, \"b\"=>2, \"d\"=>4}
# => {\"a\"=         


        
10条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 10:26

    Sort hash by key, return hash in Ruby

    With destructuring and Hash#sort

    hash.sort { |(ak, _), (bk, _)| ak <=> bk }.to_h
    

    Enumerable#sort_by

    hash.sort_by { |k, v| k }.to_h
    

    Hash#sort with default behaviour

    h = { "b" => 2, "c" => 1, "a" => 3  }
    h.sort         # e.g. ["a", 20] <=> ["b", 30]
    hash.sort.to_h #=> { "a" => 3, "b" => 2, "c" => 1 }
    

    Note: < Ruby 2.1

    array = [["key", "value"]] 
    hash  = Hash[array]
    hash #=> {"key"=>"value"}
    

    Note: > Ruby 2.1

    [["key", "value"]].to_h #=> {"key"=>"value"}
    

提交回复
热议问题