Numbers and Math
5.1 Numeric Types
42.class # Integer (arbitrary precision: 2**1000 works)
3.14.class # Float (64-bit double)
1_000_000 # underscores for readability
0xff, 0b1010, 0o17 # hex, binary, octal
1.5e3 # 1500.0
3r # Rational(3, 1)
2/3r # (2/3) Rational
3i # Complex(0, 3)
BigDecimal("0.1") # require "bigdecimal" (exact decimals for money)
5.2 Arithmetic
7 / 2 # 3 (integer division!)
7 / 2.0 # 3.5
7.fdiv(2) # 3.5
7 % 3 # 1
-7 % 3 # 2 (modulo follows the sign of the divisor)
7.divmod(2) # [3, 1]
2 ** 10 # 1024
0.1 + 0.2 # 0.30000000000000004 (floating-point!)
(0.1r + 0.2r) == 0.3r # true with Rationals
5.3 Number Methods
3.7.round # 4
3.14159.round(2) # 3.14
3.7.floor; 3.2.ceil; -3.7.truncate
10.abs; -5.abs
15.gcd(10); 4.lcm(6)
5.even?; 5.odd?; 0.zero?; 5.positive?; 5.between?(1, 10)
10.clamp(1, 5) # 5
5.times { |i| print i } # 01234
1.upto(5) { |i| print i }
10.downto(7) { |i| print i }
1.step(10, 3) { |i| print i } # 1 4 7 10
255.to_s(2) # "11111111"
"ff".to_i(16) # 255
"42".to_i; "3.5".to_f; "abc".to_i # 0 (lenient)
Integer("42"); Float("3.5") # strict (raises on invalid)
Integer("abc", exception: false) # nil
Math.sqrt(16); Math::PI; Math.log(Math::E); Math.hypot(3, 4)
rand(1..6); rand; Random.new(42).rand(100)
[1, 2, 3].sum; 10.digits # [0, 1]