Crystal, lesson 3
Your exercises receive their input on standard input (stdin), one line at a time, as if someone typed it. Crystal gives you two ways to read a line.
read_line and getsread_line returns the next line as a String, with the line break already removed. If the input
has run out, it raises an error and the program stops.
gets does the same job but returns nil when there is nothing left. Its type is therefore
String | Nil (written String?), a union type: "a String, or nil". The compiler will not
let you call string methods on it until you have dealt with the case:
2 exercises to try what you just read.
nilThis is one of Crystal's best features: forgetting about a missing value is a compile error, not a
crash at 3 a.m. When you are sure the line exists, read_line keeps things short.
Input is always text, and "7" + 1 is a compile error. Convert first:
to_i and to_f ignore spaces around the number but raise an error if the text is not a number
at all. For very large whole numbers, use to_i64.
| Expression | Result | Meaning |
|---|---|---|
7 + 2 | 9 | add |
7 - 2 | 5 | subtract |
7 * 2 | 14 | multiply |
7 / 2 | 3.5 | divide, always a Float64 |
7 // 2 | 3 | floor division, stays an integer |
7 % 2 | 1 | remainder |
2 ** 10 | 1024 | power |
Watch out for /: it returns a float even for two integers, so 10 / 2 is 5.0. Use // when
you want a whole number. (// rounds down, so -7 // 2 is -4.)
Multiplication and division happen before addition and subtraction; parentheses change the order.
Integers in Crystal have a fixed size. If a result does not fit (an Int32 tops out a little above
two billion), Crystal raises an OverflowError instead of quietly giving you a wrong number.
Mixing an integer and a float is fine: 3 * 1.5 is 4.5. To round a float, use round:
2.345.round(2) gives 2.35.
A group shares some pizza slices equally. Every person gets the same whole number of slices, and the rest are left over.
Input: two lines. The first is the number of slices (0 or more), the second the number of people (1 or more).
Output: two lines:
That sample is for the input:
Read a temperature in degrees Celsius and print it in Fahrenheit, using
F = C * 9 / 5 + 32.
Input: one line with a number, which may have a decimal part (36.6) or not (100).
Output: just the Fahrenheit value. Any normal float form is accepted, so 212.0 and 212
both count for 100 °C.
prints
name = read_line
puts "Hi, #{name}!"line = gets
if line
puts line.upcase # inside the if, Crystal knows line is a String
else
puts "no input"
endage = read_line.to_i # "42" becomes 42 (Int32)
height = read_line.to_f # "1.75" becomes 1.75 (Float64)Each person gets 3 slices.
Leftover: 214
43798.6