Ruby Array
2 min readMar 19, 2021
Ruby Array
Arrays are ordered, integer-indexed collections of any object.
Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array — -that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.
Creating Arrays
A new array can be created by using the literal constructor [] and ::new
. Arrays can contain different types of objects. For example, the array below contains an Integer, String and Float etc.
- Using literal Constructor:
arr = [1, “two”, 3.0] #=> [1, “two”, 3.0] - Using ::new:
ary = Array.new #=> []
Array.new(3) #=> [nil, nil, nil] one argument (the initial size of the Array)
Array.new(3, true) #=> [true, true, true] two arguments (the initial size and a default object).
Array Methods:
Array Iteration:
- Using for loop:
Ruby, like most languages, has the all-time favourite for loop. Interestingly, nobody uses it much — but let’s leave the alternatives for the next exercise. Here’s how you use a for loop in Ruby. Just run the code below to print all the values in the array.
array = [1, 2, 3, 4, 5]
for i in array
puts i
end - Using each loop:
Iteration is one of the most commonly cited examples of the usage of blocks in Ruby. The Array#each method accepts a block to which each element of the array is passed in turn. You will find that for loops are hardly ever used in Ruby, and Array#each and its siblings are the de-facto standard. We’ll go into the relative merits of using each over for loops a little later once you’ve had some time to get familiar with it. Let’s look at an example that prints all the values in an array.
array = [1, 2, 3, 4, 5]
array.each do |i|
puts i
end - Using each_with_index:
The each_with_index function in Ruby is used to Iterate over the object with its index and returns value of the given object.
colors = [‘red’, ‘green’, ‘blue’]
colors.each_with_index { |item, index| p “#{index}:#{item}” }
Output:
“0:red”
“1:green”
“2:blue”