📅  最后修改于: 2021-01-08 12:56:52             🧑  作者: Mango
Ruby具有一组内置的现代运算符。运算符是用于执行不同操作的符号。例如+,-,/,*等。
一元运算符期望一个单一的操作数继续运行。
Operator | Description |
---|---|
! | Boolean NOT |
~ | Bitwise complement |
+ | Unary plus |
例
在文件hello.rb中,编写以下代码。
#!/usr/bin/ruby -w
puts("Unary operator")
puts(~5)
puts(~-5)
puts(!true)
puts(!false)
输出:
算术运算符将数值作为操作数,并以单个值返回它们。
Operator | Description |
---|---|
+ | Adds values from both sides of the operator. |
– | Subtract values from both sides of the operator. |
/ | Divide left side operand with right side operand. |
* | Multiply values from both sides of the operator. |
** | Right side operand becomes the exponent of left side operand. |
% | Divide left side operand with right side operand returning remainder. |
例
在文件hello.rb中,编写以下代码。
#!/usr/bin/ruby -w
puts("add operator")
puts(10 + 20)
puts("subtract operator")
puts(35 - 15)
puts("multiply operator")
puts(4 * 8)
puts("division operator")
puts(25 / 5)
puts("exponential operator")
puts(5 ** 2)
puts("modulo operator")
puts(25 % 4)
输出:
按位运算符处理位操作数。
Operator | Description |
---|---|
& | AND operator |
| | OR operator |
<< | Left shift operator |
>> | Right shift operator |
^ | XOR operator |
~ | Complement operator |
逻辑运算符处理位操作数。
Operator | Description |
---|---|
&& | AND operator |
|| | OR operator |
三元运算符首先检查给定条件是对还是错,然后执行条件。
Operator | Description |
---|---|
?: | Conditional expression |
例
在文件hello.rb中,编写以下代码。
#!/usr/bin/ruby -w
puts("Ternary operator")
puts(2<5 ? 5:2)
puts(5<2 ? 5:2)
输出:
赋值运算符为操作数分配一个值。
Operator | Description |
---|---|
= | Simple assignment operator |
+= | Add assignment operator |
-= | subtract assignment operator |
*= | Multiply assignment operator |
/= | Divide assignment operator |
%= | Modulus assignment operator |
**= | Exponential assignment operator |
运算符比较两个操作数。
Operator | Description |
---|---|
== | Equal operator |
!= | Not equal operator |
> | left operand is greater than right operand |
< | Right operand is greater than left operand |
>= | Left operand is greater than or equal to right operand |
<= | Right operand is greater than or equal to left operand |
<=> | Combined comparison operator |
.eql? | Checks for equality and type of the operands |
equal? | Checks for the object ID |
例
在文件hello.rb中,编写以下代码。
#!/usr/bin/ruby -w
puts("Comparison operator")
puts(2 == 5)
puts(2 != 5)
puts(2 > 5)
puts(2 < 5)
puts(2 >= 5)
puts(2 <= 5)
输出:
范围运算符创建一系列连续值,这些连续值包括一个开始值,一个结束值和一个介于两者之间的值范围。
(..)创建一个包含最后一项的范围,而(…)创建一个不包含最后一项的范围。
例如,对于1..5范围,输出范围是1到5。
对于1 … 5的范围,输出范围为1到4。
Operator | Description |
---|---|
.. | Range is inclusive of the last term |
… | Range is exclusive of the last term |