A.5 Integer
whole numbers
A.5.1 Math Operations for the Integer Class
12 + 5 # => 17
12 - 5 # => 7
12 * 5 # => 60
12 / 5 # => 2
The /
operator for integers only returns a whole number and omits the remainder.
A.5.2 %
(modulus) operator
Integer % Integer ⇒ Integer
Returns the Integer
remainder from a divisions.
13 / 5
Returns
3
A.5.3 **
operator Integer
Integer ** Integer ⇒ Integer
Raises a number to a power.
Returns an Integer
3 ** 2 # => 9
2 ** 3 # => 8
A.5.4 .odd? and .even? method
Integer#odd? ⇒ Boolean
or
Integer#even? ⇒ Boolean
Returns a boolean(true
or false
) based on whether the integer is odd or even.
7.odd?
Returns
true
8.odd?
Returns
false
8.even?
Returns
true
7.even?
Returns
false
A.5.5 rand
Integer#rand ⇒ Float
or
Integer#rand(Integer) ⇒ Integer
or
Integer#rand(Range) ⇒ Integer
- Creates a random
Float
between 0 to 1 - Can be given an optional
Integer
argument that will generate and return anInteger
between 0 and the argument. - Can be given an optional argument of a
Range
that will generate a randomInteger
that between theRange
.
# returns => 0.21374618638...
rand 10) # returns => 7
rand(10..20)) # returns => 19 rand((
A.5.6 .to_s
Integer#to_s ⇒ String
Converts an integer to a string literal.
Returns a String
8.to_s
“8”
10) # assigns a random integer between 0 to 9 to the variable lucky_number
lucky_number = rand("My lucky number is " + lucky_number + "!" p
The above block of code won’t work and will throw an error.
TypeError (no implicit conversion of Integer into String)
This is where the .to_s
method comes handy.
10) # assigns a random integer between 0 to 9 to the variable lucky_number
lucky_number = rand("My lucky number is " + lucky_number.to_s + "!" p
“My lucky number is 7!”
"There are " + 7.to_s + " pineapples."
“There are 7 pineapples”
A.5.7 .to_f
Integer#to_f ⇒ Float
converts an integer to a Float
(decimal).
7.to_f
7.0
10 #
number = 3 # Returns => 3
p number / 3 # Returns => 3.3333333333333335 p number.to_f /