Ruby: Array basics

Mixed Types

In Ruby, you don’t have to make all of the elements of an Array be the same type:

mixed_array = [1, "two", 3.0, joe]

Indices

Arrays are 0-indexed, offset from the beginning:

a = english_alphabet[0]

Arrays accept negative indices, offset from the end:

z = english_alphabet[-1]
y = english_alphabet[-2]

Arrays accept a Range of indices:

pry> english_alphabet[0..2]
=> ["a", "b", "c"]

Array Size

You can use the Methods size, length, or count to get the number of elements in the Array:

pry> english_alphabet.length
=> 26
pry> english_alphabet.size
=> 26
pry> english_alphabet.count
=> 26

Iterating over an Array

Iterating over an Array using the each Method and a Block (recommended):

# statement-6
english_alphabet.each do |letter|
  do_something(letter)
end

You could make an equivalent Block with curly-braces { } instead do-end. The convention is to only use curly-braces if your Block is simple enough to write on 1 line:

# statement-7
english_alphabet.each {|letter| do_something(letter) }

Iterating over an Array using a for-loop and indices:

# statement-8
for i in 0...english_alphabet.length
  letter = english_alphabet[i]
  do_something(letter)
end

Notice that in statement-8 we have to use 3 dots (...) in our Range because we want to exclude the last number: english_alphabet.length. For example, while looping over an Array of size 4, we want to loop over the indices 0, 1, 2, and 3, but not 4, because 4 is not an index of the Array.

You can list all of the methods available for an Array (it has almost 200):

english_alphabet.methods