Introduction To Ruby
Arrays

Array Literals

An array literal is a comma-separated list of values that is enclosed in square brackets. If the elements of the array are strings, they are normally quoted. We use array literals as a quick way to define all of the elements of an array in a compact way.

The following example shows some of the different ways you can make an array with literals. You can also see the effect of print and puts statements when performed on the array. At the end of each example you can see how to output individual elements of the array.

# Array Literals

# array of integers
triangular = [0,1,3,6,10,15,21]
puts "Triangular Numbers"
print triangular
print "\n"
puts triangular[0] # first element

# array of strings
words = ['is', 'this', 'a', 'question']
puts "Array Of Strings"
print words
print "\n"
puts words[1] # second element

# convert a range to array
nums = (4..10).to_a
puts "Array defined by range"
print nums
print "\n"
puts nums[1..3] # 2nd to 4th elements

letters = ('a'..'z').to_a
puts "String array defined by range"
print letters
print "\n"
puts letters[5..10] # 6th to 10th elements

# nested arrays
arraynest = [['zero', 'one', 'two'],['three', 'four', 'five'], ['six', 'seven', 'eight']]
puts "Nested (2 dimensional) array"
print arraynest
print "\n"
puts arraynest[1][1] # 2nd element from 2nd array

# separated with white space
morewords = %w[the quick brown fox]
puts "Array defined using %w"
print morewords
print "\n"

gets

Array.new

You can also create an array using the Array.new statement. Remember that the elements are always numbered from 0.

# Array.new Examples

empty_array = Array.new
print "Empty Array: " + empty_array.to_s + "\n"

tennils = Array.new(10)
print "Ten elements, all nil: " + tennils.to_s + "\n"

minusone = Array.new(10,-1)
print "Ten elements, all -1: " + minusone.to_s + "\n"

gets

Array Size

To find out how many elements there are in an array, you find its size. The size is always one more than the subscript of the last element. The following example exploits that fact to define an array of Fibonacci numbers.

# Fibonacci Sequence

fibs = [0,1]
print "Fibonacci Numbers: " + fibs.to_s + "\n"
puts fibs.size

for i in fibs.size..fibs.size+7 do
  fibs[fibs.size] = fibs[i-2] + fibs[i-1]
end

print "Fibonacci Numbers: " + fibs.to_s + "\n"
puts fibs.size

gets

Array Operators

Strictly speaking, the square brackets are an opertor. There are a handful of other operators that can be used with arrays.

# Array Operators

# some arrays
evens = [0,2,4,6,8]
odds = [1,3,5,7,9]
squares = [1,4,9]

# concatenation
allofthem = evens + odds
print evens.to_s + "+" + odds.to_s + "=" + allofthem.to_s + "\n\n"

# subtraction
oddsquares = squares - evens
print squares.to_s + "-" + evens.to_s + "=" + oddsquares.to_s + "\n\n"

# multiplication
s = squares*2
print squares.to_s + "*2=" + s.to_s + "\n\n"

# boolean - union
a = odds | evens
print odds.to_s + " | " + evens.to_s + " = " + a.to_s + "\n\n"

# boolean - intersection
b = odds & squares
print odds.to_s + " & " + squares.to_s + " = " + b.to_s + "\n\n"

gets

Array Methods

Ruby defines a lot of handy methods for working with arrays. The following table examples shows a few of them.

# Array Methods

# some arrays
empty_array = []
letters = ('a'..'e').to_a
nums = [1,1,2,2,3,3,4,4]
morenums = [3,1,4,5,2]

# empty?

if empty_array.empty? then
  print "empty_array is empty\n"
end

if letters.empty? then
  print "letters is empty\n"
else
  print "letters is not empty\n"
end

# sample()

5.times do
  print "2 random elements from " + morenums.to_s + ": "
  print morenums.sample(2).to_s + "\n\n"
end

# include?()

print "Does " + letters.to_s + " contain c? " + letters.include?('c').to_s + "\n"
print "Does " + letters.to_s + " contain f? " + letters.include?('f').to_s + "\n\n"

# sort

print morenums.to_s + " sorted to " + morenums.sort.to_s + "\n\n"

# shuffle

print letters.to_s + " shuffled to " + letters.shuffle.to_s + "\n\n"

# push and pop

print letters.to_s + ".pop = "
letters.pop
print letters.to_s + "\n\n"

print letters.to_s + ".push('e') = "
letters.push('e')
print letters.to_s + "\n\n"

gets

Challenges

  1. Initialise an array of 10 names. Output the array to the screen in reverse order.
  2. Declare an array of 10 integers. Allow the user to input the values they want. Output the sum, largest, smallest and mean values from their list.
  3. Declare an array of 7 integers. Initialise each element to 0. Use a loop and random numbers to simulate the rolling of a single die. If a 1 is rolled, increase the value of element 1 in the array by 1, if a 2 is rolled, increase the value of element 2 by 1. When all 200 rolls have been simulated, output the tally to the console.
  4. Write a program to choose 100 random numbers between 1 and 100. Count and display how many numbers are in the range 1-10, 11-20, 21-30 etc.