Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How can we get the length of a hash in Ruby

okwudili onyejiaku

Overview

We can use the length property to find the length of a Hash in Ruby.

Syntax

hash.length

Return value

This method returns the count of entries in the hash.

Code example

# create some hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {name: "okwudili", stack: "ruby"}
h3 = {"foo": 0, "bar": 1}
h4 = {M:"Mango", A: "Apple", B: "Banana"}
h5 = {}
# get the length of 
# hashes and print results
puts h1.length  # 3
puts h2.length  # 2
puts h3.length  # 2
puts h4.length  # 3
puts h5.length  # 0
Get the length of a hash in Ruby

Code explanation

  • Lines 2–6: We create some Hashes —h1,h2,h3,h4, and h5.
  • Lines 9–13: We find the length of each hash, using the length property. Then, we print the results to the console.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring