Arrays
Array creation, appending (<<), mapping/selecting/summing, and iterating with each.
Simple enough for a 5-year-old to understand
Create and append to array
colors = ["red", "purple"]colors << "green"p colorsputs colors.lengthArray creation, appending (<<), mapping/selecting/summing, and iterating with each.
Simple enough for a 5-year-old to understand
colors = ["red", "purple"]colors << "green"p colorsputs colors.lengthIn Ruby, an array is an ordered collection of objects and can hold values of different types. Its size is not predetermined; it grows and shrinks as needed. An array is also an object, so there are numerous methods available on it.
Ruby's greatest power with arrays is its iterator methods. There are separate methods for iterating through elements one by one, transforming, filtering, and reducing them. Using these methods is both shorter and safer than writing manual loops.
A point to watch out for is negative indices: minus one gives the LAST element. This provides convenience, but when a calculated index accidentally falls into the negative, instead of an error, it returns an element from the end of the array, and the bug propagates silently.
If you want to transform elements and get a new array, use map; if you want to filter, use select; if you just want to do something for each element, use each.
Writing manual counter loops over an array is not common in Ruby and carries the risk of off-by-one errors; iterator methods are both concise and safe.
Wrong
numbers = [1, 2, 3]
doubled = numbers.each { |n| n * 2 }
puts doubled.inspecteach does not perform transformation; it discards the block's result and returns the ORIGINAL array. An unchanged array is printed to the screen, and no error message is received. map is used for a new transformed array; confusing these two is very common.
Correct
numbers = [1, 2, 3]
doubled = numbers.map { |n| n * 2 }
puts doubled.inspectWrong
numbers = [1, 2, 3] puts numbers[10].round
An out-of-bounds index does not throw an error, it returns nil; then when a method is called on nil, you get the "undefined method 'round' for nil" error. The error surfaces a step away from the actual cause. To catch the error early, the fetch method is used.
Correct
numbers = [1, 2, 3] value = numbers.fetch(10, 0) puts value.round
Wrong
numbers = [1, 2, 3, 4] numbers.each do |n| numbers.delete(n) if n.even? end puts numbers.inspect
Deleting elements while iteration is ongoing shifts the iterator's position and elements are skipped; the result turns out different than expected. There is no error message, the work is done incompletely and silently. Ruby's correct tool is the reject method: it produces a filtered new array.
Correct
numbers = [1, 2, 3, 4]
numbers = numbers.reject { |n| n.even? }
puts numbers.inspecteach executes the block for each element and returns the original array; it does not transform. map, on the other hand, collects the RESULT of the block on each call and produces a new array. If you want a new list of values, use map; if you only want a side effect, use each.
Ruby's design choice: if the index is out of bounds, it returns nil. This provides flexibility but delays errors. If you want the error to appear immediately, use fetch: if the index doesn't exist, it raises an error directly or returns the default value you provide.
dup produces a shallow copy: the array is new, but the elements are the same objects. In nested arrays, modifying inner arrays is reflected in both copies. For a true deep copy, serializing with Marshal and deserializing is a common way.
Arrays can grow and hold values of different types together.
Negative indices count from the end; minus one is the last element.
map transforms, select filters, each only iterates.
Out-of-bounds indices return nil instead of an error; fetch reveals the error early.