Learn/Crystal/8. Strings and a small project
Lesson 8 of 8
Sign in

Crystal, lesson 8

Strings and a small project

Text is everywhere: names, commands, messages. Crystal strings are UTF-8 and immutable: every method that seems to change a string actually returns a new one, and the original stays as it was.

Everyday string methods

size counts characters, not bytes, so accented letters count as one each.

Characters

Indexing a string with a single number gives a Char, written in single quotes. chars turns a whole string into an array of them, which opens up every array method from the last lesson:

Char has its own handy methods, such as letter?, digit?, upcase and downcase.

2 exercises to try what you just read.

Exercise 1

Shout, flip and count

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

Splitting and joining

Lining text up

rjust pads on the left and ljust on the right, which is how you build neat columns: "42".rjust(5) is " 42", and "tea".ljust(6, '.') is "tea...".

Bundling data with record

The final exercise needs to keep three facts about each item together. Crystal's record macro creates a small, immutable data type in one line:

You can also add methods to it by giving record a block, with def inside, just like the methods you wrote in lesson 6.

Putting it all together

The project below uses every lesson so far: reading input, converting numbers, a method or two, an array of records, block methods like sum and max_by to total things up, a decision for an empty receipt, and interpolation for the output. A good plan: read N; parse each line with split into an Item; print one line per item; then sum the quantities and line totals. For the biggest line, max_by returns the first item when two are equal.

Further reading

  • API: String and Char
  • Crystal reference: String literals
  • API: top-level macros, including record

Read one line of text and print three lines:

  1. the text in uppercase,
  2. the text reversed,
  3. Vowels: N, where N counts the letters a e i o u in either case.

Input: one line (letters, spaces and punctuation; it may be empty).

prints

Print a receipt for a shopping trip.

Input: the first line is the number of items N (0 or more). Each of the next N lines has an item name (one word), a quantity and a unit price in whole euros, separated by spaces.

Output:

  • one line per item, in input order: name xQTY = LINE_TOTAL,
  • then Items: and the sum of all quantities,
  • then Total: and the sum of all line totals,
  • then Biggest: and the name of the item with the largest line total (the first one if there is a tie), or none if there are no items.

prints

s = "Hello, Crystal"

s.upcase                 # "HELLO, CRYSTAL"
s.downcase               # "hello, crystal"
s.size                   # 14 characters
s.reverse                # "latsyrC ,olleH"
s.includes?("Crystal")   # true
s.starts_with?("He")     # true
s.gsub("l", "L")         # "HeLLo, CrystaL" (replace every match)
s.sub("l", "L")          # "HeLlo, Crystal" (only the first)
s[0, 5]                  # "Hello" (start at 0, take 5)
s[-7..]                  # "Crystal" (from 7th-last to the end)
s[0]                     # 'H', a Char
"banana".chars.count { |c| c == 'a' }   # 3
"aeiou".includes?('e')                  # true: a string can contain a Char
"red,green,blue".split(",")   # ["red", "green", "blue"]
["a", "b", "c"].join("-")     # "a-b-c"
"ab" * 3                      # "ababab"
record Item, name : String, qty : Int32, price : Int32

apple = Item.new("apple", 3, 2)
puts apple.name                # apple
puts apple.qty * apple.price   # 6
Hello there
HELLO THERE
ereht olleH
Vowels: 4
3
apple 3 2
bread 1 4
cheese 2 5
apple x3 = 6
bread x1 = 4
cheese x2 = 10
Items: 6
Total: 20
Biggest: cheese