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}

--

--

Alessio Bussolari

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