Ruby, lesson 3
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.
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.
Input always arrives as text. "4" + "5" is "45", not 9, because adding two strings joins
them. Convert first:
2 exercises to try what you just read.
.to_i"42".to_i42.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.
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.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3 |
% | remainder | 7 % 2 | 1 |
** | power | 7 ** 2 | 49 |
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.
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".
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 + bnums = gets.split.map(&:to_i) # "3 10 7" becomes [3, 10, 7]
first, second, third = nums # unpack into three variablesprice = 10.0 / 3
puts format("%.2f", price) # 3.33
puts price.round(1) # 3.3Each person pays 33
Left over: 1100
3Average: 85.00