Hashes are a fundamental data structure in Ruby that allow you to store key-value pairs. In this guide, we will explore everything you need to know about Ruby Hashes, from creating and accessing them to manipulating and iterating over them.
To create a new Hash in Ruby, you can use the following syntax:
hash = { key1: value1, key2: value2 }
You can also use the Hash.new
method to create an empty Hash:
hash = Hash.new
You can access values in a Hash by using the key associated with the value. For example:
hash = { name: "John", age: 30 }
puts hash[:name] # Output: John
puts hash[:age] # Output: 30
There are several methods available for manipulating Hashes in Ruby. Some common methods include:
merge
: Combines two Hashes into a new Hashdelete
: Removes a key-value pair from a Hashclear
: Removes all key-value pairs from a HashYou can iterate over a Hash using the each
method. This method allows you to access both the key and value of each key-value pair in the Hash. For example:
hash = { name: "Jane", age: 25 }
hash.each do |key, value|
puts "#{key}: #{value}"
end
Hashes are a powerful data structure in Ruby that allow you to store and manipulate key-value pairs efficiently. By understanding how to create, access, manipulate, and iterate over Hashes, you can take full advantage of this versatile data structure in your Ruby programs.
© 2024 RailsInsights. All rights reserved.