Skip to content
Justice Tech School

Arrays and Hashes

Arrays are ordered lists and hashes hold key value pairs. Blocks with each, map, select and reduce make iteration elegant.

Example
fruits = ["apple", "banana"]
fruits << "cherry"
puts fruits.length, fruits.first
user = { name: "Ada", age: 21 }
user[:city] = "Lagos"
user.each { |k, v| puts "#{k}: #{v}" }
nums = [1, 2, 3, 4, 5, 6]
puts nums.map { |n| n * 2 }.inspect
puts nums.select(&:even?).inspect
puts nums.sum, nums.reduce(:*)

Result

3
apple
name: Ada
age: 21
city: Lagos
[2, 4, 6, 8, 10, 12]
[2, 4, 6]
21
720

Exercise

Transform each item.

nums. { |n| n * 2 }

Quiz Test

How do you append to an array?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.