Ruby operators


Ruby supports a rich set of operators. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method pointing to variable a is called with b as an argument to the method call.

For each operator (+ - * / % ** & | ^ << >> && ||), there is a corresponding abbreviated assignment operator (+= -= etc).

Ruby arithmetic operators

Assume that the value of variable a is 10 and the value of variable b is 20, then:

##-Subtraction - subtract the right operand from the left operand a - b will get -10*Multiplication - Multiply the operands on both sides of the operator a * b will get 200/ Division - divide the left operand by the right operand b / a will get 2%Modulo - divide the left operand by the right operand and return the remainder b % a will get 0**Exponent - perform exponential calculationa**b will get 10 raised to the 20th power

Ruby comparison operator

Assume that the value of variable a is 10 and the value of variable b is 20, then:

OperatorDescriptionExample
+Addition - Add the operands on both sides of the operator a + b will get 30
Operator DescriptionExample
==Checks whether the values ​​of the two operands are equal. If they are equal, the condition is true. . (a == b) is not true.
!= Checks whether the values ​​of the two operands are equal. If they are not equal, the condition is true. (a != b) is true.
>Checks whether the value of the left operand is greater than the value of the right operand, if so, the condition is true. (a > b) is not true.
<Checks whether the value of the left operand is less than the value of the right operand, if so the condition is true. (a < b) is true.
>=Checks whether the value of the left operand is greater than or equal to the value of the right operand, if so the condition is true. (a >= b) is not true.
<=Checks whether the value of the left operand is less than or equal to the value of the right operand, if so the condition is true. (a <= b) is true.
<=>Union comparison operator. Returns 0 if the first operand is equal to the second operand, 1 if the first operand is greater than the second operand, and -1 if the first operand is less than the second operand. (a <=> b) Returns -1.
=== Used to test equality within the when clause of a case statement. (1...10) === 5 returns true.
.eql?Returns true if the receiver and parameter have the same type and equal values. 1 == 1.0 returns true, but 1.eql?(1.0) returns false.
equal?Returns true if the receiver and parameter have the same object id. If aObj is a copy of bObj, then aObj == bObj returns true, a.equal?bObj returns false, but a.equal?aObj returns true.

Ruby assignment operator

Assume that the value of variable a is 10 and the value of variable b is 20, then:

Operator DescriptionExample
=Simple assignment operator, assigns the value of the right operand to the left operand c = a + b will assign the value of a + b to c
+=Addition and assignment operator, the right operand The result of adding the left operand is assigned to the left operand c += a which is equivalent to c = c + a
-= minus and Assignment operator, assigns the result of subtracting the right operand from the left operand to the left operand c -= a is equivalent to c = c - a
*= Multiplication and assignment operator, assigns the result of multiplying the right operand by the left operand to the left operandc *= a is equivalent to c = c * a
/=The division and assignment operator assigns the result of dividing the left operand by the right operand to the left operandc /= a is equivalent to c = c / a
%= Modulo and assignment operator, find the modulus of two operands and assign it to the left operand c %= a is equivalent to c = c % a
**= exponent and assignment operator, performs exponent calculation and assigns the value to the left operand c **= a is equivalent to c = c ** a

Ruby Parallel Assignment

Ruby also supports parallel assignment of variables. This allows multiple variables to be initialized with a single line of Ruby code. For example:

a = 10
b = 20
c = 30

Use parallel assignment to declare faster:

a, b, c = 10, 20, 30

Parallel assignment is also useful when exchanging the values ​​of two variables:

a, b = b, c

Ruby bit operators

Bitwise operators act on bits and perform operations bit by bit.

Suppose if a = 60, and b = 13, now in binary format, they look like this:

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^ b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators supported by Ruby.

##|If present in any operand, binary OR operation character is copied into the result. (a | b) will get 61, which is 0011 1101^ if present in one of the operands but not both The binary XOR operator copies one of the two operands into the result. (a ^ b) will get 49, which is 0011 0001~The two's complement operator is a unary operator with " Flip" bit effect. (~a ) will get -61, which is 1100 0011, 2's complement, signed binary number. <<Binary left shift operator. The value of the left operand is shifted left by the number of bits specified by the right operand. a << 2 will get 240, which is 1111 0000##>>

Ruby logical operators

The following table lists the logical operators supported by Ruby.

Assume that the value of variable a is 10 and the value of variable b is 20, then:

OperatorDescriptionInstance
& The binary AND operator copies one bit to the result if both operands are present. (a & b) will get 12, which is 0000 1100
Binary right shift operator. The value of the left operand is shifted to the right by the number of bits specified by the right operand. a >> 2 will get 15, which is 0000 1111
OperatorDescription Example
and is called the logical AND operator. The condition is true if both operands are true. (a and b) is true.
or is called the logical OR operator. The condition is true if either of the two operands is non-zero. (a or b) is true.
&& is called the logical AND operator. The condition is true if both operands are non-zero. (a && b) is true.
|| is called the logical OR operator. The condition is true if either of the two operands is non-zero. (a || b) is true.
! is called the logical NOT operator. Used to reverse the logical state of the operand. The logical NOT operator will make the condition false if it is true. !(a && b) is false.
not is called the logical NOT operator. Used to reverse the logical state of the operand. The logical NOT operator will make the condition false if it is true. not(a && b) is false.

Ruby Ternary Operator

Having more than one operation is called a ternary operator. The first one calculates the true or false value of the expression, and then decides to execute one of the following two statements based on this result. The syntax of conditional operators is as follows:

## ? :Conditional expressionIf the condition is true? then the value is X: otherwise the value is Y
OperatorDescriptionInstance
##Ruby Range Operators

In Ruby, sequence ranges are used to create a contiguous range of values ​​- including a starting value, an ending value (as appropriate), and the values ​​between them.

In Ruby, these sequences are created using the ".." and "..." range operators. The range created by the two-point form contains the start value and the end value, and the range created by the three-point form only contains the start value and does not include the end value.

Operator.....

Ruby defined? Operator

defined? is a special operator that determines whether the passed expression has been defined in the form of a method call. It returns a string describing the expression, or nil if the expression is undefined.

The following are various usages of the defined? operator:

Usage 1

defined? variable # 如果 variable 已经初始化,则为 True

For example:

foo = 42
defined? foo    # => "local-variable"
defined? $_     # => "global-variable"
defined? bar    # => nil(未定义)

Usage 2

defined? method_call # 如果方法已经定义,则为 True

For example:

defined? puts        # => "method"
defined? puts(bar)   # => nil(在这里 bar 未定义)
defined? unpack      # => nil(在这里未定义)

Usage 3

# 如果存在可被 super 用户调用的方法,则为 True
defined? super

For example:

defined? super     # => "super"(如果可被调用)
defined? super     # => nil(如果不可被调用)

Usage 4

defined? yield   # 如果已传递代码块,则为 True

For example:

defined? yield    # => "yield"(如果已传递块)
defined? yield    # => nil(如果未传递块)

Ruby dot operator" ." and the double colon operator "::"

You can call a module method by preceding the method name with the module name and an underscore. You can reference a constant using the module name and two colons.

:: is a unary operator that allows constants, instance methods, and class methods to be defined within a class or module and accessible from anywhere outside the class or module.

Remember: In Ruby, classes and methods can also be treated as constants.

You only need to prefix the constant name of the expression with :: to return the appropriate class or module object.

If no prefix expression is used, the main Object class is used by default.

The following are two examples:

MR_COUNT = 0        # 定义在主 Object 类上的常量
module Foo
  MR_COUNT = 0
  ::MR_COUNT = 1    # 设置全局计数为 1
  MR_COUNT = 2      # 设置局部计数为 2
end
puts MR_COUNT       # 这是全局常量
puts Foo::MR_COUNT  # 这是 "Foo" 的局部常量

The second example:

CONST = ' out there'
class Inside_one
   CONST = proc {' in there'}
   def where_is_my_CONST
      ::CONST + ' inside one'
   end
end
class Inside_two
   CONST = ' inside two'
   def where_is_my_CONST
      CONST
   end
end
puts Inside_one.new.where_is_my_CONST
puts Inside_two.new.where_is_my_CONST
puts Object::CONST + Inside_two::CONST
puts Inside_two::CONST + CONST
puts Inside_one::CONST
puts Inside_one::CONST.call + Inside_two::CONST

Ruby operator precedence

The following table is based on the precedence of operators All operators are listed from highest level to lowest level.

DescriptionInstance
Create a range from the start point to the end point (including the end point) 1..10 Create a range from 1 to 10
Create a range from the start point to the end point (excluding the end point) 1...10 Create a range from 1 to 9
## are ^ | bit XOR, bit ORis<= < > >=Comparison operatoris< ;=> == === != =~ !~Equality and pattern matching operators (!= and !~ cannot be defined as methods)&&logical AND||logical OR .. ...Range (inclusive, exclusive)? :三元 if-then-else= %= { /= -= += |= &= >>= <<= *= &&= ||= **=Assignmentlogical composition

Note: The operators identified as in the method column are actually methods and therefore can be overloaded.

MethodOperatorDescription
is ::Constant parsing operator
is[ ] [ ]=Element reference, element collection
is**index
is! ~ + -Non, complement, one dollar plus, one dollar minus (the last two methods are named +@ and -@)
is * / %Multiplication, division, modulus
is+ -Addition and subtraction
is>> <<bit shift right, bit shift left
is The & bit and






##defined?
Check whether the specified symbol has been defined

not
Logical negation
##or and