1. Introduction
In Ruby, a hash is a collection of key-value pairs. Sometimes, it's necessary to find out the number of key-value pairs present in the hash, i.e., its size. This post will demonstrate how to find the size of a hash in Ruby.
2. Program Steps
1. Create a hash with key-value pairs.
2. Use the size method to get the size of the hash.
3. Print the size.
3. Code Program
# Creating a hash with some key-value pairs
book = {
"title" => "To Kill a Mockingbird",
"author" => "Harper Lee",
"year" => 1960,
"genre" => "Fiction"
}
# Finding the size of the hash
number_of_entries = book.size
# Printing the size of the hash
puts "The number of entries in the hash is: #{number_of_entries}"
Output:
The number of entries in the hash is: 4
Explanation:
1. A hash is created with four key-value pairs.
2. The size method is used on the hash, which returns the number of key-value pairs. In this case, it returns 4.
3. The result is printed out using the puts method.
Comments
Post a Comment