Open In App

How can we access the entries of a Hash in Ruby?

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

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

Ruby
# 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.

Ruby
# 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

Ruby
# 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"}

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads