Learn/Crystal/3. Reading input and arithmetic
Lesson 3 of 8
Sign in

Crystal, lesson 3

Reading input and arithmetic

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 gets

read_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.

Exercise 1

Pizza party

Press Ctrl Enter or Check to test your code.

Exercise 2

Celsius to Fahrenheit

Press Ctrl Enter or Check to test your code.

nil

This 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.

Text to numbers

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.

Arithmetic

ExpressionResultMeaning
7 + 29add
7 - 25subtract
7 * 214multiply
7 / 23.5divide, always a Float64
7 // 23floor division, stays an integer
7 % 21remainder
2 ** 101024power

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.

Further reading

  • API: IO#gets and IO#read_line
  • API: String#to_i and String#to_f
  • Crystal reference: Operators
  • Crystal reference: Union types

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"
end
age = 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: 2
14
4
37
98.6