How to Sort a Hash in Ruby?
Last Updated :
26 Mar, 2024
In this article, we will learn how to sort a Hash in ruby. We can sort the map by key, from low to high or high to low, using the sortBy method.
Syntax:
sorted_hash = original_hash.sort_by { |key, value| expression }.to_h
Example 1: In this example, we sort a hash in ascending order
Ruby
# Define a hash
hash = {"Zash" => 30, "Jhavesh" => 20, "Charlie" => 50}
# Sort the hash by value in ascending order
sorted_hash = hash.sort_by { |_, value| value }.to_h
puts sorted_hash
# Output: {"Jhavesh"=>20, "Zash"=>30, "Charlie"=>50}
Output{"Jhavesh"=>20, "Zash"=>30, "Charlie"=>50}
Example 2: In this example we sort a Hash by Values in Descending Order
Ruby
# Define a hash
hash = {"Zash" => 30, "Jhavesh" => 20, "Charlie" => 50}
# Sort the hash by value in descending order
sorted_hash_desc = hash.sort_by { |_, value| -value }.to_h
puts sorted_hash_desc
# Output: {"Charlie"=>50, "Zash"=>30, "Jhavesh"=>20}
Output{"Charlie"=>50, "Zash"=>30, "Jhavesh"=>20}
Example 3: In this example we sort a Hash by Keys in Ascending Order
Ruby
# Define a hash
hash = {"Zash" => 30, "Jhavesh" => 20, "Charlie" => 50}
# Sort the hash by key in ascending order
sorted_hash_keys = hash.sort_by { |key, _| key }.to_h
puts sorted_hash_keys
# Output: {"Charlie"=>50, "Jhavesh"=>20, "Zash"=>30}
Output{"Charlie"=>50, "Jhavesh"=>20, "Zash"=>30}
Share your thoughts in the comments
Please Login to comment...