What is an Array?
The Array class is an ordered, indexed collection of objects. They are mutable, meaning you can modify the elements of an array after it has been created.
Example:
# Creating an array with three elements
my_array = [1, "hello", 3.14]
# Accessing elements by index
puts my_array[0] # Output: 1
puts my_array[1] # Output: hello
puts my_array[2] # Output: 3.14
# Modifying elements
my_array[1] = "world"
puts my_array # Output: [1, "world", 3.14]
# Adding elements to the end of the array
my_array.push("new element")
puts my_array # Output: [1, "world", 3.14, "new element"]
How and when to use the Array class?
You use the Array class when you need to store and manage a collection of items, especially when the order of elements matters.
1) List of items: Arrays are great for representing lists of items.
user_names = ["Alice", "Bob", "Charlie"]
2) Data Transformation: Arrays are often used to transform or process data. You can iterate over the elements and apply operations or filters.
numbers = [1, 2, 3, 4, 5]
squared_numbers = numbers.map { |num| num**2 }
3) Collection of Objects: Arrays can hold objects of different types, making them versatile for storing heterogeneous collections.
mixed_data = [1, "hello", 3.14, { key: "value" }]
4) Stack or Queue: Arrays can be used as a simple stack or queue where you add or remove elements from one end.
stack = []
stack.push(1)
stack.push(2)
popped_element = stack.pop
5) Working with API Responses: When dealing with API responses, you might use arrays to represent a list of items returned by the API.
require 'json'
require 'net/http'
api_url = URI.parse('https://api.example.com/data')
api_response = Net::HTTP.get(api_url)
data_array = JSON.parse(api_response)
Top comments (0)