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

Crystal, lesson 7

Collections

Programs rarely work with one value at a time. Crystal's two everyday collections are the Array (an ordered list) and the Hash (a dictionary of keys and values).

Arrays

Every array has an element type, here Int32, and the compiler makes sure you only put integers in it. An empty array has nothing to infer from, so you state the type: names = [] of String.

Reading past the end with scores[10] raises an IndexError. When an index might be missing, use scores[10]?, which returns nil instead.

Working with arrays through blocks

Arrays come with a huge set of methods. Most take a block:

map transforms every item, select keeps the items that pass a test, and , and fold the array into one value. These cover most of what you would otherwise write loops for.

2 exercises to try what you just read.

Exercise 1

Score stats

Press Ctrl Enter or Check to test your code.

Exercise 2

Vote tally

Press Ctrl Enter or Check to test your code.

sum
max
count

When the block just calls one method on each item, there is a shortcut: &.method. So words.map { |w| w.upcase } can be written words.map(&.upcase).

Hashes

A Hash maps keys to values:

Reading a missing key with stock["kiwi"] raises a KeyError. For counting, create a hash with a default value, so missing keys start at zero:

A Crystal hash remembers the order in which keys were first added. To print in another order, sort first: counts.keys.sort gives the keys alphabetically, and counts.to_a.sort gives {key, value} pairs sorted by key.

From a line of text to an array

split with no arguments breaks a string on runs of whitespace: "4 8 15".split gives ["4", "8", "15"]. Then .map(&.to_i) turns every piece into a number.

Further reading

  • Crystal reference: Array literals
  • Crystal reference: Hash literals
  • API: Array, Hash and Enumerable

Read a line of game scores separated by spaces and print four statistics.

Input: one line with at least one whole number. Output:

That is for the input 12 6 21 3.

A class votes for the name of its pet fish. Count the votes for each name.

Input: the first line is the number of votes N (0 or more). Then N lines follow, each with one name (a single word).

Output: one line per name, name: votes, sorted alphabetically by name. If there are no votes, print No votes.

prints

scores = [72, 95, 88]       # Array(Int32)
scores << 60                # append: [72, 95, 88, 60]
puts scores.size            # 4
puts scores[0]              # 72 (indexes start at 0)
puts scores[-1]             # 60 (negative counts from the end)
p scores                    # [72, 95, 88, 60]
scores.sum                      # 315
scores.max                      # 95
scores.sort                     # [60, 72, 88, 95]
scores.map { |s| s + 5 }        # [77, 100, 93, 65]
scores.select { |s| s >= 80 }   # [95, 88]
scores.count { |s| s < 75 }     # 2
scores.each_with_index { |s, i| puts "#{i}: #{s}" }
stock = {"apple" => 3, "pear" => 0}   # Hash(String, Int32)
stock["plum"] = 7                     # add or replace
puts stock["apple"]                   # 3
puts stock.fetch("kiwi", 0)           # 0 for a missing key
puts stock.has_key?("pear")           # true
counts = Hash(String, Int32).new(0)
["tea", "coffee", "tea"].each { |drink| counts[drink] += 1 }
p counts   # {"tea" => 2, "coffee" => 1}
Count: 4
Min: 3
Max: 21
Sum: 42
4
Bubbles
Finn
Bubbles
Nemo
Bubbles: 2
Finn: 1
Nemo: 1