Ruby算术运算符 #
一、算术运算符概述 #
Ruby支持标准的算术运算符,可以对数字进行各种数学运算。
| 运算符 | 描述 | 示例 |
|---|---|---|
| + | 加法 | 1 + 2 = 3 |
| - | 减法 | 5 - 3 = 2 |
| * | 乘法 | 3 * 4 = 12 |
| / | 除法 | 10 / 3 = 3 |
| % | 取余 | 10 % 3 = 1 |
| ** | 幂运算 | 2 ** 3 = 8 |
二、基本运算 #
2.1 加法 #
ruby
1 + 2
3.14 + 2.86
"Hello" + " World"
[1, 2] + [3, 4]
2.2 减法 #
ruby
5 - 3
10.5 - 3.5
Time.now - 3600
2.3 乘法 #
ruby
3 * 4
2.5 * 4
"Ruby " * 3
2.4 除法 #
ruby
10 / 3
10.0 / 3
10 / 3.0
10.fdiv(3)
2.5 取余 #
ruby
10 % 3
-10 % 3
10 % -3
10.5 % 3
2.6 幂运算 #
ruby
2 ** 3
2 ** 10
4 ** 0.5
2 ** -1
三、整数除法 #
3.1 整数除法特点 #
ruby
10 / 3
10 / 3.0
10.0 / 3
10.to_f / 3
3.2 divmod方法 #
ruby
10.divmod(3)
10.divmod(-3)
-10.divmod(3)
3.3 fdiv方法 #
ruby
10.fdiv(3)
7.fdiv(2)
四、取余运算详解 #
4.1 取余规则 #
ruby
10 % 3
-10 % 3
10 % -3
-10 % -3
4.2 modulo方法 #
ruby
10.modulo(3)
-10.modulo(3)
4.3 remainder方法 #
ruby
10.remainder(3)
-10.remainder(3)
10.remainder(-3)
-10.remainder(-3)
五、幂运算详解 #
5.1 整数幂 #
ruby
2 ** 10
10 ** 6
5.2 分数幂 #
ruby
4 ** 0.5
8 ** (1/3.0)
27 ** (1/3.0)
5.3 负数幂 #
ruby
2 ** -1
10 ** -2
六、一元运算符 #
6.1 正号 #
ruby
+5
+(-5)
a = 5
+a
6.2 负号 #
ruby
-5
-(-5)
a = 5
-a
七、运算方法 #
7.1 方法形式 #
ruby
1.+(2)
1.send(:+, 2)
10./(3)
10.%(3)
2.**(10)
7.2 自定义运算 #
ruby
class Point
attr_reader :x, :y
def initialize(x, y)
@x, @y = x, y
end
def +(other)
Point.new(x + other.x, y + other.y)
end
def -(other)
Point.new(x - other.x, y - other.y)
end
def *(scalar)
Point.new(x * scalar, y * scalar)
end
def to_s
"(#{x}, #{y})"
end
end
p1 = Point.new(1, 2)
p2 = Point.new(3, 4)
puts p1 + p2
puts p1 - p2
puts p1 * 2
八、数学函数 #
8.1 Math模块 #
ruby
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)
8.2 常用方法 #
ruby
-5.abs
3.14.round
3.14.round(1)
3.5.floor
3.5.ceil
3.14.to_i
九、运算优先级 #
9.1 优先级规则 #
ruby
2 + 3 * 4
(2 + 3) * 4
2 ** 3 ** 2
(2 ** 3) ** 2
9.2 优先级表 #
| 优先级 | 运算符 |
|---|---|
| 高 | ** |
| + - (一元) | |
| * / % | |
| 低 | + - (二元) |
十、实用示例 #
10.1 温度转换 #
ruby
def celsius_to_fahrenheit(c)
c * 9 / 5.0 + 32
end
def fahrenheit_to_celsius(f)
(f - 32) * 5 / 9.0
end
celsius_to_fahrenheit(0)
celsius_to_fahrenheit(100)
fahrenheit_to_celsius(32)
fahrenheit_to_celsius(212)
10.2 计算圆的面积 #
ruby
def circle_area(radius)
Math::PI * radius ** 2
end
def circle_circumference(radius)
2 * Math::PI * radius
end
circle_area(5)
circle_circumference(5)
10.3 勾股定理 #
ruby
def hypotenuse(a, b)
Math.sqrt(a ** 2 + b ** 2)
end
hypotenuse(3, 4)
hypotenuse(5, 12)
10.4 阶乘 #
ruby
def factorial(n)
return 1 if n <= 1
(1..n).reduce(:*)
end
factorial(5)
factorial(10)
10.5 组合数 #
ruby
def combination(n, r)
factorial(n) / (factorial(r) * factorial(n - r))
end
combination(5, 2)
combination(10, 3)
十一、总结 #
本章我们学习了:
- 基本运算:加、减、乘、除、取余、幂
- 整数除法:/、divmod、fdiv
- 取余运算:%、modulo、remainder
- 幂运算:**、分数幂、负数幂
- 一元运算符:+、-
- 运算方法:运算符的方法形式
- 数学函数:Math模块
接下来让我们学习Ruby的比较运算符!
最后更新:2026-03-27