Crystal, lesson 8
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.
size counts characters, not bytes, so accented letters count as one each.
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.
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...".
recordThe 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.
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.
Read one line of text and print three lines:
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:
name xQTY = LINE_TOTAL,Items: and the sum of all quantities,Total: and the sum of all line totals,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 # 6Hello thereHELLO THERE
ereht olleH
Vowels: 43
apple 3 2
bread 1 4
cheese 2 5apple x3 = 6
bread x1 = 4
cheese x2 = 10
Items: 6
Total: 20
Biggest: cheese