Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Practice: Crystal Exercises with Solutions

Practice Crystal with eight exercises on collections, blocks, macros, channels and JSON, each with a hint, a Crystal solution and a runnable Ruby version to experiment with.

The best way to learn a language is to write programs. These exercises cover the second half of the course: collections, blocks, macros, fibers, channels and data formats. Try each one before opening the solution, and write the type of every method you create, since the compiler will check it for you.

The Crystal compiler is not available on this site. Each exercise shows the Crystal solution read-only, and a runnable Ruby version lets you test the idea and change the inputs. Expect small differences: Ruby has no static types and raises errors at run time where Crystal refuses to compile.

Exercise 1: word frequencies

Write word_counts(text : String) : Hash(String, Int32) that lowercases the text, splits it into words (letters only) and counts each word. Then print the three most frequent words, ties broken alphabetically.

Hint: scan(/[a-z']+/), Hash.new(0) and sort_by { |w, c| {-c, w} } (a tuple sorts element by element).

CRYSTAL
def word_counts(text : String) : Hash(String, Int32)
  counts = Hash(String, Int32).new(0)
  text.downcase.scan(/[a-z']+/) { |m| counts[m[0]] += 1 }
  counts
end

text = "the cat and the hat and the bat"
top = word_counts(text).to_a.sort_by { |word, count| {-count, word} }.first(3)
top.each { |word, count| puts "#{word}: #{count}" }
Ruby Ruby version: word frequencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Exercise 2: group anagrams

Given ["listen", "silent", "enlist", "google", "gogole", "cat", "act"], return the groups of words that are anagrams of each other, largest group first.

Hint: the sorted letters of a word are the same for all its anagrams, so use them as the key of group_by.

CRYSTAL
words = ["listen", "silent", "enlist", "google", "gogole", "cat", "act"]
groups = words.group_by { |w| w.chars.sort.join }.values
groups.sort_by { |g| {-g.size, g.first} }.each { |g| puts g.join(", ") }
Ruby Ruby version: anagram groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Exercise 3: a retrying block

Write a method retry_times(attempts, &block) that calls the block and, if it raises, tries again up to attempts times, returning the block's value on success and re-raising the last error otherwise. Test with a block that fails twice and then succeeds.

Hint: a loop with begin ... rescue, a counter, and yield. In Crystal, give the block its return type with a generic: def retry_times(attempts : Int32, & : -> T) : T forall T.

CRYSTAL
def retry_times(attempts : Int32, & : -> T) : T forall T
  tries = 0
  begin
    tries += 1
    yield
  rescue ex
    retry if tries < attempts
    raise ex
  end
end

calls = 0
value = retry_times(3) do
  calls += 1
  raise "flaky" if calls < 3
  "ok after #{calls} calls"
end
puts value
Ruby Ruby version: retry_times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Exercise 4: an attr_with_history macro

Write a macro property_with_history name, Type that defines a getter, a setter and a method name_history returning every previous value. Using it must look like:

CRYSTAL
class Thermostat
  property_with_history temperature, Int32
end
t = Thermostat.new
t.temperature = 20
t.temperature = 22
t.temperature_history   # [20]

Hint: {{name.id}}, @{{name.id}}, and an array of the declared type. Use {{type}} inside Array({{type}}).

CRYSTAL
macro property_with_history(name, type)
  @{{name.id}} : {{type}}?
  @{{name.id}}_history = [] of {{type}}

  def {{name.id}} : {{type}}?
    @{{name.id}}
  end

  def {{name.id}}=(value : {{type}})
    if old = @{{name.id}}
      @{{name.id}}_history << old
    end
    @{{name.id}} = value
  end

  def {{name.id}}_history : Array({{type}})
    @{{name.id}}_history
  end
end
Ruby Ruby version: the macro as a class method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Exercise 5: parallel sum with channels

Split the numbers 1 to 1000 into four chunks, sum each chunk in its own fiber, send the partial sums to a channel and add them up. The answer must be 500500.

Hint: each_slice(250), one spawn per slice, and receive exactly as many values as you spawned fibers.

CRYSTAL
numbers = (1..1000).to_a
partials = Channel(Int32).new

chunks = numbers.each_slice(250).to_a
chunks.each do |chunk|
  spawn { partials.send(chunk.sum) }
end

total = chunks.size.times.sum { partials.receive }
puts total      # 500500
Ruby Ruby version: parallel sum with a queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Exercise 6: typed JSON config

Define a Server class with host : String, port : Int32 = 8080 and tls : Bool = false, parse it from JSON, and show a helpful error when port is not a number.

CRYSTAL
require "json"

class Server
  include JSON::Serializable
  getter host : String
  getter port : Int32 = 8080
  getter tls : Bool = false
end

begin
  s = Server.from_json(%({"host": "example.com"}))
  puts "#{s.host}:#{s.port} tls=#{s.tls}"
  Server.from_json(%({"host": "example.com", "port": "http"}))
rescue ex : JSON::ParseException
  puts "Invalid config: #{ex.message}"
end
Ruby Ruby version: defaults and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Exercise 7: an iterator of Fibonacci numbers

Build a class Fibonacci that includes Iterator(Int32) (or an equivalent method that returns an iterator) so you can write Fibonacci.new.first(10) and Fibonacci.new.select(&.even?).first(5) without computing more numbers than you need.

CRYSTAL
class Fibonacci
  include Iterator(Int32)

  def initialize
    @a = 0
    @b = 1
  end

  def next
    value = @a
    @a, @b = @b, @a + @b
    value
  end
end

p Fibonacci.new.first(10)
p Fibonacci.new.select(&.even?).first(5)
Ruby Ruby version: an infinite generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Exercise 8: your own challenge

Choose one of these and build it with the project lessons as a model:

  1. A grep-like tool: mygrep PATTERN FILE that prints matching lines with their numbers, using OptionParser for -i (ignore case) and -n.
  2. A concurrent link checker that takes URLs on standard input, checks them with a pool of 8 workers using HTTP::Client and a 5-second timeout, and prints a table.
  3. A #[Table]-style macro that turns a class with typed fields into a SQL CREATE TABLE statement using reflection.
  4. A tiny key-value server speaking a line protocol (SET a 1, GET a) over TCPServer, one fiber per connection.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In exercise 1, why sort by the tuple {-count, word}?

    The negated count sorts descending and the word breaks ties.
  2. 2. What goes wrong if a worker fiber raises and nobody rescues it?

    Always rescue inside the fiber and report the failure.
  3. 3. Why does the macro in exercise 4 use .id?

    name.id turns the macro argument into a bare identifier usable in def and @ivar names.
  4. 4. How many values must the main fiber receive in exercise 5?

    Each fiber sends exactly one partial sum, so four receives collect them all.

Summary

  • Collections: group_by, tally, sort_by with tuples solve most counting and grouping tasks.
  • Blocks and generics let you write helpers such as retry_times that work for any return type.
  • Macros generate repetitive definitions using {{ }} and .id.
  • Fibers plus channels split work; count your receives or close your channels.
  • Typed JSON gives validation for free.

Next: Crystal tutorial home