0
0
Rubyprogramming~5 mins

Hash methods (keys, values, each) in Ruby

Choose your learning style9 modes available
Introduction

Hashes store pairs of related information. These methods help you look at all the keys, all the values, or go through each pair one by one.

When you want to see all the names or labels stored in a hash.
When you need to get all the stored data values without their keys.
When you want to do something with every key and value in the hash, like printing or changing them.
Syntax
Ruby
hash.keys
hash.values
hash.each { |key, value| ... }

keys returns an array of all keys.

values returns an array of all values.

each lets you run code for every key-value pair.

Examples
Shows all keys: [:a, :b, :c]
Ruby
my_hash = {a: 1, b: 2, c: 3}
puts my_hash.keys.inspect
Shows all values: [1, 2, 3]
Ruby
my_hash = {a: 1, b: 2, c: 3}
puts my_hash.values.inspect
Prints each key and value pair on its own line.
Ruby
my_hash = {a: 1, b: 2, c: 3}
my_hash.each { |key, value| puts "#{key} => #{value}" }
Sample Program

This program shows how to get all keys, all values, and then prints each key with its value.

Ruby
person = {name: "Anna", age: 30, city: "Paris"}

puts "Keys:"
puts person.keys.inspect

puts "Values:"
puts person.values.inspect

puts "Each key-value pair:"
person.each do |key, value|
  puts "#{key}: #{value}"
end
OutputSuccess
Important Notes

The keys and values methods return arrays you can use like any other array.

The each method does not change the hash; it just lets you look at each pair.

Summary

keys gives you all the keys in an array.

values gives you all the values in an array.

each lets you do something with every key and value.