Collections in Ruby: Arrays, Hashes, and Sets


Introduction to Collections

Collections in Ruby are data structures that allow you to store and manipulate multiple values. They are an essential part of programming and enable you to work with groups of related data. In this guide, we'll explore three common collection types in Ruby: Arrays, Hashes, and Sets, along with examples.


Arrays

An array is an ordered collection of elements. It can store any data type, including numbers, strings, and objects. Here's an example of creating and using an array:


# Creating an array
my_array = [1, 2, 3, 4, 5]
# Accessing elements
puts my_array[0] # Output: 1
# Modifying elements
my_array << 6 # Add 6 to the end
my_array[1] = 10 # Update the second element
# Iterating through an array
my_array.each do |element|
puts element
end

Hashes

A hash is a collection of key-value pairs, where each key is unique. Hashes are useful for associating data with specific identifiers. Here's an example of creating and using a hash:


# Creating a hash
my_hash = { "name" => "John", "age" => 30, "city" => "New York" }
# Accessing values
puts my_hash["name"] # Output: John
# Modifying values
my_hash["age"] = 31 # Update age to 31
my_hash["country"] = "USA" # Add a new key-value pair
# Iterating through a hash
my_hash.each do |key, value|
puts "#{key}: #{value}"
end

Sets

A set is an unordered collection of unique elements. Sets are helpful when you need to ensure uniqueness and perform set operations. Here's an example of creating and using a set:


require 'set'
# Creating a set
my_set = Set.new([1, 2, 3, 4, 4, 5])
# Adding and removing elements
my_set.add(6)
my_set.delete(3)
# Checking for membership
puts my_set.include?(4) # Output: true
# Set operations
other_set = Set.new([4, 5, 6, 7])
union = my_set | other_set # Union
intersection = my_set & other_set # Intersection

Conclusion

Collections, including arrays, hashes, and sets, are essential tools for organizing and manipulating data in Ruby. Each collection type has its unique characteristics and use cases. Understanding how to work with collections is crucial for building efficient and data-driven applications.


Practice using collections in your Ruby programs to become a proficient Ruby developer. For more information, refer to the official Ruby documentation.


Happy coding!