A striking red ruby, representing the Ruby programming language, is elegantly placed between two curly braces, symbolizing the use of hash or block structures in Ruby. The image has a simple, elegant background with subtle programming motifs and a hint of Ruby red color scheme.
Ruby and Curly Braces: Symbolizing Structure and Flexibility in Code

10 Essential Ruby Hash Methods Explained

Alessio Bussolari
3 min readNov 29, 2023

--

Hashes are a cornerstone of Ruby programming, offering a flexible and efficient way to store and manipulate key-value pairs. Understanding how to effectively work with hashes is vital for Ruby developers. This article dives into 10 essential methods for managing hashes in Ruby, each illustrated with practical examples.

.each

Iterating Over Key-Value Pairs

The .each method allows you to iterate over each key-value pair in a hash.

hash = {a: 1, b: 2, c: 3}
hash.each { |key, value| puts "#{key} => #{value}" }
# a => 1
# b => 2
# c => 3

.keys

Getting All Keys

.keys returns an array of all keys in the hash.

hash = {a: 1, b: 2, c: 3}
puts hash.keys # => [:a, :b, :c]

.values

Getting All Values

.values gives you an array of all the values in the hash.

hash = {a: 1, b: 2, c: 3}
puts hash.values # => [1, 2, 3]

.delete

Removing a Key-Value Pair

.delete removes a key-value pair from the hash by key.

hash = {a: 1, b: 2, c: 3}
hash.delete(:b)
puts hash # => {:a=>1, :c=>3}

.merge

Combining Hashes

.merge combines two hashes, returning a new hash.

hash1 = {a: 1, b: 2}
hash2 = {c: 3, d: 4}
combined = hash1.merge(hash2)
puts combined # => {:a=>1, :b=>2, :c=>3, :d=>4}

.has_key?

Checking for a Key

.has_key? checks if a hash contains a specific key.

hash = {a: 1, b: 2, c: 3}
puts hash.has_key?(:b) # => true

.has_value?

Checking for a Value

.has_value? determines if a hash contains a specific value.

hash = {a: 1, b: 2, c: 3}
puts hash.has_value?(2) # => true

.fetch

Accessing Values with a Fallback

.fetch retrieves a value for a given key, with an option for a fallback if the key is not…

--

--

Alessio Bussolari

Ruby on Rails programmer since 2009. Current CTO at COSMIC SRL, where I lead the team in creating innovative solutions.