Ruby Tutorial
Ruby CGI
Ruby Advanced
1. Creating an Array
In Ruby, you can create an array by placing a comma-separated series of objects between square brackets []
. For example:
arr = [1, 2, 3, 4, 5]
This creates an array arr
that contains the integers 1 through 5.
2. Accessing Array Elements
You can access the elements of an array by referring to the index number.
arr = [1, 2, 3, 4, 5] puts arr[0] # outputs 1 puts arr[2] # outputs 3
Remember that array indices start at 0 in Ruby, so arr[0]
refers to the first element of the array.
3. Modifying Array Elements
You can modify an existing element of an array by using its index number.
arr = [1, 2, 3, 4, 5] arr[0] = 10 puts arr # outputs [10, 2, 3, 4, 5]
4. Adding Elements to an Array
You can add an element to the end of an array using the push
method or <<
operator.
arr = [1, 2, 3, 4, 5] arr.push(6) arr << 7 puts arr # outputs [1, 2, 3, 4, 5, 6, 7]
5. Removing Elements from an Array
You can remove an element from an array using the pop
method (which removes the last element) or the delete_at
method (which removes an element at a specified index).
arr = [1, 2, 3, 4, 5] arr.pop puts arr # outputs [1, 2, 3, 4] arr.delete_at(0) puts arr # outputs [2, 3, 4]
6. Iterating over an Array
You can iterate over the elements of an array using the each
method.
arr = [1, 2, 3, 4, 5] arr.each do |i| puts i end
This will print out each element in the array on its own line.
7. Finding the Length of an Array
You can find the length (number of elements) of an array using the length
or size
method.
arr = [1, 2, 3, 4, 5] puts arr.length # outputs 5 puts arr.size # outputs 5
These are the basics of working with arrays in Ruby. Arrays are very flexible in Ruby, and you can put different types of data in them (like strings, numbers, and other arrays). You can also call various methods on arrays to manipulate and query them.
Creating and initializing Arrays in Ruby:
[]
.my_array = [1, 2, 3, 4, 5]
Array literals and constants in Ruby:
array_literal = %w(apple banana cherry) MY_CONST_ARRAY = [10, 20, 30].freeze
Accessing elements in Ruby Arrays:
fruits = ["apple", "banana", "cherry"] first_fruit = fruits[0]
Adding and removing elements from Arrays in Ruby:
push
, pop
, shift
, and unshift
for adding and removing elements.fruits = ["apple", "banana", "cherry"] fruits.push("orange") fruits.pop
Iterating over Arrays in Ruby:
each
or map
or using a loop.numbers = [1, 2, 3, 4, 5] numbers.each { |num| puts num }
Common Array methods in Ruby:
sort
, reverse
, and include?
for common array operations.numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5] sorted_numbers = numbers.sort contains_five = numbers.include?(5)
Multi-dimensional Arrays in Ruby:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Sorting and searching in Ruby Arrays:
sort
method for sorting arrays and include?
or index
for searching.numbers = [5, 2, 8, 1, 3] sorted_numbers = numbers.sort index_of_8 = numbers.index(8)