Arrays

Ref. WGR Chapter 9, Section 9.2, Collection handling with arrays

Array

Arrays act like stacks

a = [1, 2, 3]
a.push "four" #=> [1, 2, 3, "four"]
a.pop         #=> "four"
a             #=> [1, 2, 3]

or like queues

a = [1, 2, 3]
a.push(4)        #=> [1, 2, 3, 4]
a.shift          #=> 1
a                #=> [1, 2, 3]

a.unshift "zero" #=> ["zero", 1, 2, 3]

or like sets

a = [1, 2, 3]
a.include?(2)  #=> true

(technically an array is not a set because it doesn't enforce uniqueness)

first and last

a[0]          #=> 1
a.first       #=> 1
a[a.size-1]   #=> 3
a.last        #=> 3

Adding to an array

a = []
a << "x"       #=> ["x"]

<< (pronounced "shovel") does a push -- adds an item to the end of an array -- DESTRUCTIVE!

a = []
a + ["x"]       #=> ["x"]

+ does a concat -- adds two arrays together and makes a new array -- safe!

plus-equals

size isn't everything

Accessing array items

Arrays are zero-indexed

fruit = ["apple", "banana", "cherry"]
fruit[0] #=> "apple"
fruit[2] #=> "cherry"
fruit[3] #=> nil

Question: which is better?

zero-based indexing

or

one-based indexing?

Zero Is Better Than One

array indexing

Fun with Array Indexes

fruit = ["apple", "banana", "cherry", "date"]

negative indexes count from the back

fruit[-1] #=> "date"
fruit[-3] #=> "banana"

range indexes

fruit[1..3]  #=> ["banana", "cherry", "date"]
fruit[1...3] #=> ["banana", "cherry"]

getting out of bounds

>> a = ["apple", "banana", "cherry"]
=> ["apple", "banana", "cherry"]
>> a.length
=> 3
>> a[5]
=> nil
>> a.size
=> 3
>> a
=> ["apple", "banana", "cherry"]

moral: getting past the end returns nil, not error

setting out of bounds

>> a
=> ["apple", "banana", "cherry"]
>> a[9] = "jicama"
=> "jicama"
>> a.size
=> 10
>> a
=> ["apple", "banana", "cherry", nil, nil,
    nil, nil, nil, nil, "jicama"]

moral: setting past the end autofills with nil

Multidimensional arrays (aka matrices)

Next: Ranges >> << Previous: Collections

Outline

[contents]

Arrays Slides - Code Like This

/

#