Arrays – lists of things
An array is a list. You write it with square brackets, the elements separated by commas:
breakfast = ["egg", "toast"]
breakfast.lengthWith square brackets you access an element – counting starts at 0! Negative numbers count from the end, and asking for a position that doesn't exist gives you nil:
puts breakfast[0]
puts breakfast[-1]
breakfast[5]With << (the “shovel”) you append to the end, with each you walk through it:
breakfast << "coffee"
breakfast.each do |item|
puts item
endArrays have lots of useful methods. To look at their results, use p instead of puts: puts would write every element on a line of its own, while p shows the array the way Ruby sees it – with brackets and commas:
numbers = [5, 3, 8, 1, 3]
p numbers.sort # sorted
p numbers.reverse # reversed
p numbers.uniq # without duplicates
p numbers.include?(8) # in there?
p numbers.sum # the sum
p numbers.max # the largest
numbers.first(2) # the first twoNone of these methods changes numbers – each returns a new result. Check it: afterwards numbers is still [5, 3, 8, 1, 3]. If you want to sort the array itself, there's sort! with an exclamation mark. In Ruby the exclamation mark is a warning: “careful, this method changes the object.”
Two handy helpers work hand in hand: join glues the elements into one string, split cuts a string into an array. And %w[...] is shorthand for an array of words:
animals = %w[fox cat hedgehog]
puts animals.join(", ")
"bacon,egg,toast".split(",")If you also need the position while walking through, use each_with_index: the block then gets two parameters, the element and its number:
animals.each_with_index do |animal, i|
puts "#{i + 1}. #{animal}"
endA variable name is a label stuck on an object, not a box. same = breakfast sticks a second label on the same array – dup makes a new one. show_objects draws it with arrows:
breakfast = ["egg", "toast"]
same = breakfast # a second label on the same array
copy = breakfast.dup # a new array
same << "juice"
show_objects(breakfast: breakfast, same: same, copy: copy)Now breakfast has juice too – and copy does not. But look at the strings: the copy points at the same "egg". dup copies the array, not what is in it.
By the way, an array may hold anything, mixed too: numbers, strings, nil – even other arrays: [[1, 2], [3, 4]] is a little table with two rows.
"bacon" to the array below. Then the cell should show the breakfast sorted and joined with commas: bacon, egg, toast.breakfast = ["egg", "toast"]
# ...
no_duplicates – the items without duplicates, sorted; bacon_count – how often bacon is on the list (count takes the word you look for as its argument); and first_last – an array of the list's first and last item.shopping = ["bacon", "egg", "toast", "bacon", "coffee", "egg", "bacon"]
# no_duplicates = ... # without duplicates, sorted
# bacon_count = ... # how often bacon is on the list
# first_last = ... # the first and the last item, as an array