Rails Insights

Learn Ruby Hash: Complete Guide

Introduction

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.

Creating a Hash

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

Accessing Values in a Hash

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

Manipulating a Hash

There are several methods available for manipulating Hashes in Ruby. Some common methods include:

  • merge: Combines two Hashes into a new Hash
  • delete: Removes a key-value pair from a Hash
  • clear: Removes all key-value pairs from a Hash

Iterating Over a Hash

You 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

Conclusion

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.

Published: May 29, 2024

© 2024 RailsInsights. All rights reserved.