Skip to content
Arrays
step 1/5

Reading — step 1 of 5

Learn

~1 min readCollections

Arrays are ordered collections of any type:

nums = [1, 2, 3, 4]
puts nums.length    # 4
puts nums[0]         # 1
puts nums[-1]        # 4 — negative indexes from the end
nums << 5            # append; same as nums.push(5)
puts nums.first(2).inspect   # [1, 2]

The Enumerable methods are where Ruby shines — they take blocks and chain elegantly:

nums.map { |n| n * n }              # [1, 4, 9, 16, 25]
nums.select { |n| n.even? }          # [2, 4]
nums.reject { |n| n.odd? }           # [2, 4]
nums.reduce(0) { |sum, n| sum + n }  # 15
nums.reduce(:+)                       # 15 — symbol-to-proc shorthand
nums.partition { |n| n.even? }       # [[2, 4], [1, 3, 5]]

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…