Arrays and hashes are essential data structures in Ruby used to organize and store data. This chapter explores how to create, access, and manipulate these structures effectively.
Arrays in Ruby are ordered, integer-indexed collections of any object. Here's how to create and manipulate an array:
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
Elements in an array are accessed by their index:
puts numbers[0] # Outputs 1
puts names[2] # Outputs Charlie
You can add elements to arrays using push or the << operator:
numbers.push(6)
names << "David"
Use each to iterate over elements:
names.each do |name|
puts "Hello, #{name}!"
end
Hashes in Ruby are collections of key-value pairs. They are similar to dictionaries in other languages.
ages = { "Alice" => 30, "Bob" => 25, "Charlie" => 35 }
Access values in a hash by using their keys:
puts ages["Alice"] # Outputs 30
Add new pairs to hashes like this:
ages["David"] = 28
Iterate over key-value pairs using each:
ages.each do |name, age|
puts "#{name} is #{age} years old."
end