How to get all hash keys at once in Ruby
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.
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 hashesh1 = {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 resultsputs "#{h1.keys}"puts "#{h2.keys}"puts "#{h3.keys}"puts "#{h4.keys}"
Explanation
- Lines 2-5: We create four hashes.
- Lines 9-12: We use the
keysproperty to get the keys of the hashes. We use theputsfunction to print the result.