Arrays
Create and index
Arrays hold ordered collections. Indexes start at 0.
colors = ["red", "green", "blue"]
puts colors[1]
colors << "yellow"
puts colors.length
Enumerate
each is the everyday loop over arrays.
colors.each do |color|
puts color.upcase
end
Transform and select
Enumerable methods return new arrays.
nums = [1, 2, 3, 4]
puts nums.map { |n| n * 2 }.inspect
puts nums.select { |n| n.even? }.inspect
Array tips
- Negative indexes count from the end
nilis returned for missing indexes- Use
push/popandshift/unshiftas needed - Prefer clear Enumerable methods over manual index loops
Comments
One comment per signed-in account. Comments are saved with this page’s URL.