Array is the most basic data type in many programming language, in this article we will learn how to use Array in Ruby language. Array is a data type that is meant to describe a collection of values and can be used to store a list of values in a single variable. You can fill any data/value to array, be it number, string or anything. And you don’t have to put it in order. Here’s some example:

# Array contain number
my_array = [1,2,4,5,6,7]

# Array contain string
my_skills = ["HTML5","CSS3","Rails","iOS","Android"]

You may notice the array of strings above has to many Quotation marks (“). Unlike integer data type, it’s pain to write strings value into array. Fortunately, we can use the following syntax to make it more easy.

# Array contain string
my_skills = %w[HTML5 CSS3 Rails iOS Android]

Access Array by Index

Each element in array has an index, in all programming language, the index mostly start at index 0, then continue with index 1, index 2, and so on. We can directly access a value in array by call it’s index. See this example:

# Define array
my_skills = ["HTML5","CSS3","Rails","iOS","Android"]

# Call index
my_skills[0]

On the example above, it will return “HTML5″. Since:

index 0 = HTML5
index 1 = CSS3

index 4 = Android

Arrays of Arrays

We can put anything in array, so is it possible to put arrays in an array? The answers is “Yes”, and we call it Multidimensional Array. Let’s see the example of Multidimensional Array below:

# Define multidimensional array
multi_array = [[1,2,3,4],[5,6,7,8]]

Iteration in Array

Iteration over array is easy. Remember that array elements are indexed starting at 0, and always go up by one. Ruby has a method called .each to loop through array. The structure is:

array_name.each { |element| action }

See this example:

# Define array
color_array = ["Red","Blue","Yellow"]

# Print each values
color_array.each { |x| puts "#{x}\n" }

Result:

Red
Blue
Yellow

Explanation:

colorarray.each – array named colorarray given method .each

|x| - is the placeholder, we can use any placeholder

puts "#{x} " - is the action for each element


Written by Irfan Fadilah – Author at 41studio.

Read more at the source