Ruby: Array Class Flashcards
Access the first item of an array.
[1, 2, 3, 4, 5].first
[1, 2, 3, 4, 5][0]
More:
.first also takes parameters (positive numbers)
.first(4) returns the first 4 items from an array
.first does not edit/change the array, only display
Access the last item of an array.
[1, 2, 3, 4, 5].last
[1, 2, 3, 4, 5][-1]
More:
.last also takes parameters (positive numbers)
.last(3) returns the last 3 slots from an array
.last does not edit the array, only display
How do you retrieve items from an array?
You must use it’s index (number).
Note: You can ONLY use numbers to get items out of a Array.
Index an array with a non-negative integer, and it returns the object at that position or returns nil if nothing is there. Index an array with a negative integer, and it counts from the end.
How do you retrieve multiple items from an array (Paired Indexing)?
You do paired indexing providing a starting point, and a number of items to return.
a[start, count]
Example:
a = [ 1, 3, 5, 7, 9 ]
a[1,3] #=> [3,5,7]
a[3, 1] # => [7]
a[-3, 2] # => [5, 7]
How do you index an array using ranges?
a = [ 1, 3, 5, 7, 9 ] a[1..3] # => [3, 5, 7] a[1...3] # => [3, 5] a[3..3] # => [7] a[-3..-1] # => [5, 7, 9]
How to set items in an array?
You use the [ ]= operator.
a=[1,3,5,7,9]
a[1] = ’bat’ → [1, “bat”, 5, 7, 9]
a[-3] = ’cat’ → [1, “bat”, “cat”, 7, 9]
a[3] = [ 9, 8 ] → [1, “bat”, “cat”, [9, 8], 9]
a[6] = 99 → [1, “bat”, “cat”, [9, 8], 9, nil, 99]
Any gaps that result will be filled with nil
How do you replace multiple items in an array using the [ ]= operator?
The operator takes both a start and a length.
If the length is 0, the right side is inserted into the array before the start position; not items are inserted.
a = [1,2,3,4,5,6,7,8,9,10]
a[4,0] = 17
a # calls variable
[1,2,3,4,17,5,6,7,8,9,10]
if the length is nil, the value replaces at the point
a = [1,2,3,4,5,6,7,8,9,10]
a[4] = 17
a # calls variable
[1,2,3,4,17,6,7,8,9,10]
if the length is greater than 0, it replaces with what is on the right and removes the amount of spaces from the original array
a = [1,2,3,4,5,6,7,8,9,10]
a[4,4] = 17,16,16,18,19 #added 5 items, removed 4 slots
a # calls variable
[1,2,3,4,17,16,16,18,19,9,10]
How do you add “item” to the end of an array?
array.push “item”
array «_space;“item”
How do you remove an item from the end of an array?
array.pop
.push
Adds item to end of array.
.pop
Removes items from end of array.
How do you add elements to the beginning of an array?
.unshift
How do you remove objects from the beginning of an array?
.shift
.shift
Removes items from the beginning of an array.
.unshift
Add objects to beginning of array.
Example:
c = [2, 3, 4, 5]
c.unshift 1
c # calls variable
[1,2,3,4,5]