How to Extract Key and Value from Hash in Ruby

09/20/2021

Contents

In this article, you will learn how to extract key and value from hash in Ruby.

How to extract key and value from hash

In Ruby, a Hash is a collection of key-value pairs where each key is unique. You can access the values stored in a Hash by using their keys. Here’s how you can extract the key and value from a Hash:

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

# Extracting keys and values using each method
my_hash.each do |key, value|
  puts "Key: #{key}, Value: #{value}"
end

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

# Extracting keys and values using keys and values methods
keys = my_hash.keys
values = my_hash.values

puts "Keys: #{keys}" # Output: Keys: ["a", "b", "c"]
puts "Values: #{values}" # Output: Values: [1, 2, 3]

As you can see in the example above, the each method can be used to iterate over the Hash and extract both the key and value for each key-value pair. Alternatively, you can use the keys and values methods to extract just the keys or values separately.