looks_oneNumbers
As mentioned in previous lesson numbers can be represented by two types:
Integer-whole numbers like: 10, 27, 37 etc.
Float-numbers wih decimal points such as: 9.99, -23.1 etc.
1009.class #=> Integer
10.9.class #=> Float
Both classes are descendants of the Numeric class (more about inheritance later) and this is why they share a lot of common behaviours.
Integer.superclass #=> Numeric
Float.superclass #=> Numeric
Ruby supports a variety of math operators for performing arithmetic operations. Here are the basic arithmetic operators in Ruby:
Operator | Operation | Example | Return |
+ | Add | 2 + 3 | 5 |
- | Substract | 3 - 2 | 1 |
* | Multiply | 2 * 2 | 4 |
/ | Divide | 4 / 2 | 2 |
/ | Exponent | 3 ** 4 | 81 |
/ | Modulo | 10 % 3 | 1 |
# Add
2 + 3 #=> 5
9 + 2 #=> 11
# Subtract
3 - 2 #=> 1
2 - 3 #=> -1
# Multiply
2 * 2 #=> 4
3 * 2 #=> 6
# Divide
4 / 2 #=> 2
# Two Integers always return Integer number
10 / 3 #=> 0
2 / 4 #=> 0
# Exponent
2 ** 2 #=> 4
3 ** 4 #=> 81
# Modulus (Remainder)
9 % 3 #=> 0
10 % 3 #=> 1
Float & Integers
In Ruby, you can combine floating-point numbers (floats) with Integers in arithmetic operations, and Ruby will handle the conversion automatically. When you perform arithmetic operations involving a Float and an integer, Ruby will convert the Integer to a Float before performing the operation if necessary.
# Add
2 + 3.5 #=> 5.5
# Substract
2 - 3.5 #=> -1.5
# Multiply
2 * 2.0 #=> 4.0
# Divide
2 / 4.0 #=> 0.5
Using #to_i and #to_f method you can convert your number to different types. The only thing you need to remember is that when you converting Float to Integer, decimal places will be cut off. Ruby won't do any rounding here.
# Convert Integer number to Float number
2.to_f #=> 2.0
# Convert Float number to Integer number
2.0.to_i #=> 2
2.5.to_i #=> 2
There are many different methods you can use with numbers. Below are the most commonly used.
# Return previous number
2.pred # => 1
# Return next number
2.next # => 3
# Check if number is even
2.even? # => true
3.even? # => false
# Check if number is odd
2.odd? # => false
3.odd? # => true
# Return absolute number
21.abs # => 21
-21.abs # => 21
# This method works also for float numbers
21.37.abs # => 21.37
-21.37.abs # => 21.37
# Return number floor and ceil
9.11.floor # => 9
9.11.ceil # => 10
# Return rounded number
9.11.round # => 9
9.59.round # => 10
After this lesson you should be able to work with numbers, distinguish between integer and float types, perform basic arithmetic operations and use common used methods.