Learn/Ruby/7. Collections
Lesson 7 of 8
Sign in

Ruby, lesson 7

Collections

One variable holds one value. To hold a whole list of scores, or a price for every item on a menu, you need a collection. Ruby's two workhorses are the Array (an ordered list) and the Hash (a set of key-value pairs).

Arrays

An array is written with square brackets. Items are numbered from 0.

Arrays can hold any mix of values, but in practice you usually keep one kind of thing in each.

Walking through an array

each runs a block once per item. each_with_index also hands you the position.

%w[ant bee cat] is a shortcut for ["ant", "bee", "cat"].

Transforming and asking questions

Arrays come with dozens of useful methods. These are the ones you will reach for most:

map builds a new array from the block's results, and select keeps only the items for which the block is true. Neither changes the original. In a short block you can use to refer to the current item instead of naming it: .

2 exercises to try what you just read.

Exercise 1

Podium finish

Press Ctrl Enter or Check to test your code.

Exercise 2

Word tally

Press Ctrl Enter or Check to test your code.

it
nums.map { it * 10 }

Hashes

A hash maps keys to values. Lookups by key are fast, no matter how big the hash gets.

When the keys are fixed names, symbols are the usual choice, and Ruby has a shorter syntax for them:

A hash remembers the order you inserted keys in, so looping over it is predictable:

Counting with a hash

Hash.new(0) makes a hash whose missing keys read as 0 instead of nil. That turns counting into a one-liner per item:

Arrays can also do the whole job with tally, which returns the same hash.

Further reading

  • Ruby docs: Array
  • Ruby docs: Hash
  • Ruby docs: Enumerable (map, select, sum, tally)

The scores from a game night arrive on one line, separated by spaces. There is always at least one score. Print three lines:

Podium lists the three best scores from high to low, separated by single spaces. If there are fewer than three scores, list all of them. The example is the output for 70 15 92 88 41.

Read one line of lowercase words separated by spaces. Print every distinct word with the number of times it appears, one per line, in the order each word first appears:

That is the output for the cat sat the sat. If the line is empty, print nothing.

scores = [40, 75, 90]

puts scores[0]        # 40
puts scores[-1]       # 90  (negative indexes count from the end)
puts scores.length    # 3
p scores[5]           # nil (no error, just nothing there)

scores << 60          # add to the end
scores.push(85)       # same thing
p scores              # [40, 75, 90, 60, 85]
%w[ant bee cat].each_with_index do |animal, i|
  puts "#{i + 1}. #{animal}"
end
nums = [4, 9, 1, 7]

nums.sum                    # 21
nums.max                    # 9
nums.min                    # 1
nums.sort                   # [1, 4, 7, 9]
nums.sort.reverse           # [9, 7, 4, 1]
nums.include?(7)            # true
nums.map { |n| n * 10 }     # [40, 90, 10, 70]
nums.select { |n| n > 5 }   # [9, 7]
nums.first(2)               # [4, 9]
nums.join(", ")             # "4, 9, 1, 7"
prices = { "apple" => 0.5, "bread" => 2.25 }
prices["milk"] = 1.2            # add or update
puts prices["bread"]            # 2.25
p prices["cake"]                # nil (missing key)
puts prices.key?("apple")       # true
player = { name: "Mira", level: 7 }
puts player[:name]              # Mira
prices.each do |item, price|
  puts "#{item}: #{price}"
end
votes = Hash.new(0)
%w[red blue red green red].each { |colour| votes[colour] += 1 }
p votes      # {"red" => 3, "blue" => 1, "green" => 1}
Highest: 92
Lowest: 15
Podium: 92 88 70
the: 2
cat: 1
sat: 2