Arrays and hashes

Arrays and hashes, map / select / sort_by, fetch with a default, and other everyday Enumerable methods.

Runs in Zerethon IDE · Ruby 4.0 Official Ruby documentation ↗
main.rb
scores = [70, 95, 82]
scores << 60
puts "#{scores.sort.inspect} #{scores.first} #{scores.last} #{scores.size}"
puts scores.sort.reverse.take(2).inspect

ages = { "ada" => 36, "alan" => 41 }
ages["grace"] = 85
puts "#{ages.fetch("linus", "unknown")} #{ages.key?("alan")}"
ages.sort.each { |name, age| puts "#{name} #{age}" }

squares = (0...5).select(&:even?).map { |n| n * n }
puts squares.inspect

people = [{ name: "bob", age: 25 }, { name: "amy", age: 31 }]
puts people.sort_by { |person| -person[:age] }.map { |person| person[:name] }.inspect
puts [3, 1, 3, 2].uniq.sum, [1, 2, 3, 4].partition(&:odd?).inspect

Output

[60, 70, 82, 95] 70 60 4
[95, 82]
unknown true
ada 36
alan 41
grace 85
[0, 4, 16]
["amy", "bob"]
6
[[1, 3], [2, 4]]
  • scores[10] gives nil instead of an error; negative indexes count from the end.
  • sort returns a new array; sort! sorts in place.
  • hash[key] gives nil for a missing key; fetch(key, default) gives the default, and fetch(key) raises KeyError.
  • { name: "bob" } uses symbol keys — read them with person[:name], not person["name"].
  • &:even? is short for the block { |n| n.even? }.

Related topics

Official references