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

Ruby, lesson 3

Reading input and arithmetic

Programs get much more useful when they react to data. The simplest source of data is standard input (stdin): whatever the user types, or whatever the test feeds in.

Reading a line with gets

gets reads one line of input and returns it as a string. The line still ends with the newline character, so you almost always chain .chomp, which removes it:

When there is no more input, gets returns nil instead of a string. You will use that in lesson 5 to read until the input runs out.

Text is not a number

Input always arrives as text. "4" + "5" is "45", not 9, because adding two strings joins them. Convert first:

  • turns a string into an Integer: is .

2 exercises to try what you just read.

Exercise 1

Split the bill

Press Ctrl Enter or Check to test your code.

Exercise 2

Average score

Press Ctrl Enter or Check to test your code.

.to_i
"42".to_i
42
  • .to_f turns a string into a Float: "2.5".to_f is 2.5.
  • Both are forgiving. They ignore a trailing newline and stop at the first character that does not fit, so "12 apples".to_i is 12 and "abc".to_i is 0. If you would rather get an error for bad input, use Integer("abc"), which raises an ArgumentError.

    Several numbers on one line

    When numbers share a line, split the line into pieces and convert each one. split with no argument breaks a string on any run of spaces, and map turns every piece into a number:

    map(&:to_i) is shorthand for "call to_i on each item". You will learn map properly in lesson 7.

    Arithmetic operators

    OperatorMeaningExampleResult
    +add7 + 29
    -subtract7 - 25
    *multiply7 * 214
    /divide7 / 23
    %remainder7 % 21
    **power7 ** 249

    Watch the division. When both sides are integers, / gives an integer and throws away the fraction. Ruby rounds down toward negative infinity, so -7 / 2 is -4. If either side is a Float, you get a Float: 7 / 2.0 is 3.5. Use .to_f or fdiv (7.fdiv(2)) when you want the exact answer.

    Normal maths precedence applies: ** first, then *, / and %, then + and -. Use parentheses when in doubt. Shortcut assignments like score += 10 and lives -= 1 update a variable in place.

    Rounding for display

    Floats can show long tails such as 0.30000000000000004. To print a fixed number of decimal places, use format:

    %.2f means "a decimal number with exactly two digits after the point".

    Further reading

    • Ruby docs: Kernel#gets, Kernel#format, Integer()
    • Ruby docs: Integer
    • Ruby docs: Format specifications

    Friends split a restaurant bill in whole dollars. Read two integers, one per line: the bill total, then the number of people. Print how much each person pays (whole dollars, rounded down) and how many dollars are left over:

    That is the output for the input

    A player's three round scores arrive on one line, separated by spaces. Print their average with exactly two decimal places, like this:

    For the input 80 90 85 the output is Average: 85.00. For 1 2 2 it is Average: 1.67.

    name = gets.chomp
    puts "Hi, #{name}!"
    a = gets.to_i
    b = gets.to_i
    puts a + b
    nums = gets.split.map(&:to_i)    # "3 10 7" becomes [3, 10, 7]
    first, second, third = nums      # unpack into three variables
    price = 10.0 / 3
    puts format("%.2f", price)   # 3.33
    puts price.round(1)          # 3.3
    Each person pays 33
    Left over: 1
    100
    3
    Average: 85.00