Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
hash
key
communitycreator

How to get all hash keys at once in Ruby

okwudili onyejiaku

Overview

Getting the keys of a hash at once in Ruby is possible using the keys property. It returns a new array that contains all the keys of a hash.

g matrix key value one 1 two 2 three 3
Hashtable

Syntax

hash.keys

Parameters

The key property does not take any arguments.

Return value

The value returned is an array containing all keys of the hash, hash.

Code

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

# get all keys of the hashes
# and print results
puts "#{h1.keys}"
puts "#{h2.keys}"
puts "#{h3.keys}"
puts "#{h4.keys}"
Getting the keys of a hash in Ruby

Explanation

  • Lines 2-5: We create four hashes.
  • Lines 9-12: We use the keys property to get the keys of the hashes. We use the puts function to print the result.

RELATED TAGS

ruby
hash
key
communitycreator
RELATED COURSES

View all Courses

Keep Exploring