Ruby数字 #
一、数字类型概述 #
Ruby支持多种数字类型:
| 类型 | 类名 | 示例 |
|---|---|---|
| 整数 | Integer | 42, -17, 0xff |
| 浮点数 | Float | 3.14, -0.5, 1.0e10 |
| 有理数 | Rational | Rational(1, 3) |
| 复数 | Complex | Complex(1, 2) |
| 大数字 | BigDecimal | BigDecimal('0.1') |
二、整数(Integer) #
2.1 整数字面量 #
ruby
a = 42
b = -17
c = 0
d = 1_000_000
decimal = 255
hex = 0xff
octal = 0o377
binary = 0b11111111
2.2 整数方法 #
ruby
n = 42
n.abs
n.even?
n.odd?
n.zero?
n.positive?
n.negative?
n.to_s
n.to_s(2)
n.to_s(16)
n.to_f
n.chr
n.next
n.pred
n.times { |i| puts i }
n.upto(50) { |i| puts i }
n.downto(30) { |i| puts i }
2.3 整数运算 #
ruby
a = 17
b = 5
a + b
a - b
a * b
a / b
a % b
a.divmod(b)
a ** 2
a.fdiv(b)
a.gcd(b)
a.lcm(b)
2.4 位运算 #
ruby
a = 0b1010
b = 0b1100
a & b
a | b
a ^ b
~a
a << 2
a >> 1
2.5 大整数支持 #
Ruby的整数没有大小限制,自动处理大数:
ruby
big = 10 ** 100
puts big
puts big.class
puts big.to_s.length
三、浮点数(Float) #
3.1 浮点数字面量 #
ruby
a = 3.14
b = -0.5
c = 1.0
d = 1e10
e = 1.5e-3
f = 12.34_56
3.2 浮点数方法 #
ruby
f = 3.14159
f.abs
f.round
f.round(2)
f.ceil
f.floor
f.truncate
f.to_i
f.to_s
f.nan?
f.infinite?
f.finite?
f.zero?
f.positive?
f.negative?
3.3 浮点数运算 #
ruby
a = 3.14
b = 2.0
a + b
a - b
a * b
a / b
a ** b
a % b
a.divmod(b)
3.4 浮点数精度问题 #
ruby
0.1 + 0.2
0.1 + 0.2 == 0.3
(0.1 + 0.2 - 0.3).abs < 1e-10
sprintf("%.20f", 0.1 + 0.2)
3.5 使用BigDecimal处理精度 #
ruby
require 'bigdecimal'
a = BigDecimal('0.1')
b = BigDecimal('0.2')
c = a + b
c == BigDecimal('0.3')
c.to_s
c.to_f
四、有理数(Rational) #
4.1 创建有理数 #
ruby
r1 = Rational(1, 3)
r2 = Rational(2, 6)
r3 = 1/3r
r4 = 2.to_r
puts r1
puts r1.class
4.2 有理数运算 #
ruby
a = Rational(1, 3)
b = Rational(1, 2)
a + b
a - b
a * b
a / b
a ** 2
4.3 有理数方法 #
ruby
r = Rational(2, 6)
r.numerator
r.denominator
r.to_f
r.to_i
r.to_s
r.abs
r.round
r.floor
r.ceil
4.4 精确计算示例 #
ruby
def calculate_interest(principal, rate, years)
rate_r = Rational(rate, 100)
principal * (1 + rate_r) ** years
end
result = calculate_interest(1000, 5, 3)
puts result
puts result.to_f
五、复数(Complex) #
5.1 创建复数 #
ruby
c1 = Complex(1, 2)
c2 = Complex(3, 4)
c3 = 1 + 2i
c4 = 3.14i
c5 = Complex.polar(1, Math::PI/4)
puts c1
puts c1.class
5.2 复数运算 #
ruby
a = Complex(1, 2)
b = Complex(3, 4)
a + b
a - b
a * b
a / b
a ** 2
a.conjugate
5.3 复数方法 #
ruby
c = Complex(3, 4)
c.real
c.imaginary
c.abs
c.angle
c.phase
c.polar
c.rect
c.conjugate
c.to_s
六、数字转换 #
6.1 显式转换 #
ruby
n = 42
n.to_f
n.to_r
n.to_c
f = 3.14
f.to_i
f.to_r
f.to_c
r = Rational(1, 2)
r.to_i
r.to_f
r.to_c
6.2 隐式转换 #
ruby
1 + 2.0
Rational(1, 2) + 0.5
Complex(1, 2) + 1
6.3 字符串转数字 #
ruby
"42".to_i
"3.14".to_f
"1/3".to_r
"1+2i".to_c
Integer("42")
Float("3.14")
Rational("1/3")
Complex("1+2i")
Integer("0xff", 16)
Integer("1010", 2)
七、数学函数 #
7.1 Math模块 #
ruby
include Math
Math.sqrt(16)
Math.cbrt(27)
Math.log(10)
Math.log10(100)
Math.log2(8)
Math.exp(1)
Math.sin(Math::PI/2)
Math.cos(0)
Math.tan(Math::PI/4)
Math.asin(1)
Math.acos(0)
Math.atan(1)
Math.hypot(3, 4)
7.2 常用常量 #
ruby
Math::PI
Math::E
7.3 三角函数示例 #
ruby
def degrees_to_radians(degrees)
degrees * Math::PI / 180
end
def radians_to_degrees(radians)
radians * 180 / Math::PI
end
angle_deg = 45
angle_rad = degrees_to_radians(angle_deg)
puts "sin(#{angle_deg}°) = #{Math.sin(angle_rad)}"
八、随机数 #
8.1 rand方法 #
ruby
rand
rand(10)
rand(1..10)
rand(1...10)
rand(1.0..10.0)
8.2 Random类 #
ruby
rng = Random.new
rng.rand
rng.rand(10)
rng.rand(1..100)
rng = Random.new(42)
rng.rand(10)
rng.seed
8.3 随机数组元素 #
ruby
arr = [1, 2, 3, 4, 5]
arr.sample
arr.sample(2)
arr.shuffle
8.4 生成随机字符串 #
ruby
def random_string(length)
chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
Array.new(length) { chars.sample }.join
end
puts random_string(16)
九、数字格式化 #
9.1 sprintf/printf #
ruby
sprintf("%d", 42)
sprintf("%f", 3.14)
sprintf("%.2f", 3.14159)
sprintf("%e", 1000000)
sprintf("%x", 255)
sprintf("%b", 42)
sprintf("%o", 64)
sprintf("%+d", 42)
sprintf("%10d", 42)
sprintf("%-10d", 42)
sprintf("%010d", 42)
sprintf("%,d", 1234567)
printf("整数: %d, 浮点数: %.2f\n", 42, 3.14159)
9.2 格式化字符串 #
ruby
n = 42
f = 3.14159
"整数: #{n}"
"浮点数: #{f.round(2)}"
"十六进制: #{n.to_s(16)}"
"二进制: #{n.to_s(2)}"
"格式化: %05d" % n
"浮点: %.2f" % f
"组合: %d - %.2f" % [n, f]
9.3 数字分隔符 #
ruby
def format_number(n)
n.to_s.reverse.scan(/.{1,3}/).join(',').reverse
end
puts format_number(1234567890)
n = 1234567
n.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\1,').reverse
十、实用示例 #
10.1 进制转换 #
ruby
def convert_base(num, from_base, to_base)
num.to_i(from_base).to_s(to_base)
end
puts convert_base("ff", 16, 10)
puts convert_base("255", 10, 16)
puts convert_base("1010", 2, 10)
10.2 斐波那契数列 #
ruby
def fibonacci(n)
return n if n <= 1
fibonacci(n - 1) + fibonacci(n - 2)
end
def fibonacci_iterative(n)
a, b = 0, 1
n.times { a, b = b, a + b }
a
end
(0..10).each { |n| puts fibonacci(n) }
10.3 质数判断 #
ruby
def prime?(n)
return false if n < 2
return true if n == 2
return false if n.even?
(3..Math.sqrt(n).to_i).step(2).none? { |i| n % i == 0 }
end
(1..20).select { |n| prime?(n) }
10.4 数字分解 #
ruby
def digit_sum(n)
n.digits.sum
end
def digit_product(n)
n.digits.reduce(1, :*)
end
puts digit_sum(12345)
puts digit_product(12345)
十一、总结 #
本章我们学习了:
- 整数:字面量、方法、位运算、大整数支持
- 浮点数:精度问题、BigDecimal
- 有理数:精确分数运算
- 复数:复数运算
- 数学函数:Math模块
- 随机数:rand、Random类
- 格式化:sprintf、printf
接下来让我们学习Ruby的字符串类型!
最后更新:2026-03-27