How can we access the entries of a Hash in Ruby?
In this article, we will discuss how to access the entries of a Hash in ruby. We can access the entries of a Hash through different methods ranging from using keys, and values to each method
Table of Content
- Accessing the entries of a Hash using Hash.keys method
- Accessing the entries of a Hash using Hash.values method
- Accessing the entries of a Hash using Hash.each method
Accessing the entries of a Hash using the Hash.keys method
The method returns an array containing all the keys of the hash
Syntax:
hash.keys
Example: In this example, we use hash.keys method to return an array containing all the keys of the hash
# Define a hash
hash = { "a" => 1, "b" => 2, "c" => 3 }
# Access keys using keys method
keys = hash.keys
puts keys.inspect # Output: ["a", "b", "c"]
Output
{"name"=>"John", "age"=>30, "city"=>"New York"}
Accessing the entries of a Hash using Hash.values method
The Hash.values method is used to return an array containing all the values of the hash.
Syntax:
hash.values
Example: In this example we use hash.values to return an array containing all the values of the hash.
# Define a hash
hash = { "a" => 1, "b" => 2, "c" => 3 }
# Access values using values method
values = hash.values
puts values.inspect # Output: [1, 2, 3]
Output
{"name"=>"John", "age"=>30, "city"=>"New York"}
Accessing the entries of a Hash using Hash.each method
and is used to access the entries of a Hash
Syntax:
hash.each { |key, value| block }
Example: In this example we use Hash.each method is used to iterate over each key-value pair in the hash and print the entries
# Define a hash
hash = { "a" => 1, "b" => 2, "c" => 3 }
# Access entries using each method
hash.each { |key, value| puts "#{key}: #{value}" }
# Output:
# a: 1
# b: 2
# c: 3
Output
{"name"=>"John", "age"=>"30", "city"=>"New York"}
Contact Us