4.6 KiB
title
| title |
|---|
| Ruby Number Methods |
Ruby provides a variety of built-in methods you may use on numbers. The following is an incomplete list of integer and float methods.
Even:
Use .even? to check whether or not an integer is even. Returns a true or false boolean.
15.even? #=> false
4.even? #=> true
Odd:
Use .odd? to check whether or not an integer is odd. Returns a true or false boolean.
15.odd? #=> true
4.odd? #=> false
Ceil:
The .ceil method rounds floats up to the nearest number. Returns an integer.
8.3.ceil #=> 9
6.7.ceil #=> 7
Floor:
The .floor method rounds floats down to the nearest number. Returns an integer.
8.3.floor #=> 8
6.7.floor #=> 6
Next:
Use .next to return the next consecutive integer.
15.next #=> 16
2.next #=> 3
-4.next #=> -3
Pred:
Use .pred to return the previous consecutive integer.
15.pred #=> 14
2.pred #=> 1
(-4).pred #=> -5
To String:
Using .to_s on a number (integer, floats, etc.) returns a string of that number.
15.to_s #=> "15"
3.4.to_s #=> "3.4"
To Float:
Converts an Integer to a Float.
15.to_f #=> 15.0
Absolute value:
Returns the absolute value of the integer.
-12345.abs #=> 12345
12345.abs #=> 12345
Greatest Common Denominator:
The .gcd method provides the greatest common divisor (always positive) of two numbers. Returns an integer.
15.gcd(5) #=> 5
3.gcd(-7) #=> 1
Round:
Use .round to return a rounded integer or float.
1.round #=> 1
1.round(2) #=> 1.0
15.round(-1) #=> 20
Times:
Use .times to iterate the given block int times.
5.times do |i|
print i, " "
end
#=> 0 1 2 3 4