Open In App

How to Parse Hash in Ruby?

Last Updated : 05 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Parsing a hash in Ruby entails gaining access to its keys and values, iterating over them, and carrying out any necessary actions. The article focuses on discussing the ways to parse a hash in Ruby.

Iterating through a Hash

A hash may be iterated over using a variety of techniques, such as each, each_key, each_value, or map. Below is the Ruby program to iterate through a hash:

Ruby
hash = { "a" => 1, "b" => 2, "c" => 3 }

hash.each do |key, value|
  puts "Key: #{key}, Value: #{value}"
end

Output
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3

Accessing Hash Elements

Square brackets or the fetch method may be used to retrieve certain components inside the hash. Below is the Ruby program to access the hash elements:

Ruby
hash = { "a" => 1, "b" => 2, "c" => 3 }

puts hash["b"] # Output: 2
puts hash.fetch("c") # Output: 3

Output
2
3

Sorting a Hash

The sort_by method allows you to sort a hash according to keys or values. Below is the Ruby program to sort a hash:

Ruby
hash = { "b" => 2, "a" => 1, "c" => 3 }

sorted_by_key = hash.sort_by { |key, value| key }
sorted_by_value = hash.sort_by { |key, value| value }

puts sorted_by_key.to_h # Output: {"a"=>1, "b"=>2, "c"=>3}
puts sorted_by_value.to_h # Output: {"a"=>1, "b"=>2, "c"=>3}

Output
{"a"=>1, "b"=>2, "c"=>3}
{"a"=>1, "b"=>2, "c"=>3}

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads