Arrays

View saved

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
  • nil is returned for missing indexes
  • Use push/pop and shift/unshift as needed
  • Prefer clear Enumerable methods over manual index loops

Comments

One comment per signed-in account. Comments are saved with this page’s URL.