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.

Full explanation

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

Full explanation

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

Full explanation

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 an Integer between 0 and the argument.
  • Can be given an optional argument of a Range that will generate a random Integer that between the Range.
rand           # returns => 0.21374618638...
rand(10)       # returns => 7
rand((10..20)) # returns => 19

Full explanation

A.5.6 .to_s

Integer#to_s ⇒ String

Converts an integer to a string literal.

Returns a String

8.to_s

“8”

lucky_number = rand(10) # assigns a random integer between 0 to 9 to the variable lucky_number
p "My lucky number is " + lucky_number + "!" 

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.

lucky_number = rand(10) # assigns a random integer between 0 to 9 to the variable lucky_number
p "My lucky number is " + lucky_number.to_s + "!" 

“My lucky number is 7!”

"There are " + 7.to_s + " pineapples."

“There are 7 pineapples”

Full explanation

A.5.7 .to_f

Integer#to_f ⇒ Float

converts an integer to a Float(decimal).
7.to_f

7.0

number = 10       #  
p number / 3      # Returns => 3
p number.to_f / 3 # Returns => 3.3333333333333335

More examples

Full explanation