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}