位置:首頁 > 腳本語言 > Ruby基礎教程 > Ruby運算符

Ruby運算符

Ruby支持一係列豐富的運算符的一個現代化的語言。大多數運算符實際上是方法調用。例如,a + b的被解釋為a,
+(b)變量引用的對象的方法被稱為一個用b作為它的參數。

對於每個運算符 (+ - * / % ** & | ^ << >> && ||), 有相應的賦值運算符縮寫形式 (+= -= 等)

Ruby算術運算符:

假設變量a=10,變量b=20:

操作符 描述 例子
+ Addition - Adds values on either side of the operator a + b = 30
- Subtraction - Subtracts right hand operand from left hand operand a - b = -10
* Multiplication - Multiplies values on either side of the operator a * b = 200
/ Division - Divides left hand operand by right hand operand b / a = 2
% Modulus - Divides left hand operand by right hand operand and returns remainder b % a = 0
** Exponent - Performs exponential (power) calculation on operators a**b = 10 to the power 20

Ruby比較操作符:

假設變量a=10,變量b=20:

操作符 描述 例子
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (a == b) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a <= b) is true.
<=> Combined comparison operator. Returns 0 if first operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second. (a <=> b) returns -1.
=== Used to test equality within a when clause of a case statement. (1...10) === 5 returns true.
.eql? True if the receiver and argument have both the same type and equal values. 1 == 1.0 returns true, but 1.eql?(1.0) is false.
equal? True if the receiver and argument have the same object id. if aObj is duplicate of bObj then aObj == bObj is true, a.equal?bObj is false but a.equal?aObj is true.

Ruby賦值運算符:

假設變量a=10,變量b=20:

操作符 描述 例子
= Simple assignment operator, Assigns values from right side operands to left side operand c = a + b will assigne value of a + b into c
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
**= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a

Ruby並行賦值:

Ruby還支持並行賦值的變量。這使得多個一行Ruby代碼來初始化變量。例如:

a = 10
b = 20
c = 30

需要更迅速聲明,使用並行賦值:

a, b, c = 10, 20, 30

並行賦值交換兩個變量的值也是有用的:

a, b = b, c

Ruby位運算符:

位運算符位和位操作執行位。

假設當a =60和b=13;現在以二進製格式將如下:

a = 0011 1100

b = 0000 1101

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

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011

支持Ruby語言的位運算符

運算符 描述 實例
& Binary AND Operator copies a bit to the result if it exists in both operands. (a & b) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in either operand. (a | b) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (a ^ b) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. (~a ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. a << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. a >> 2 will give 15 which is 0000 1111

Ruby邏輯運算符:

支持Ruby語言的邏輯運算符

假設變量a=10,變量b=20:

運算符 描述 例子
and Called Logical AND operator. If both the operands are true then then condition becomes true. (a and b) is true.
or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (a or b) is true.
&& Called Logical AND operator. If both the operands are non zero then then condition becomes true. (a && b) is true.
|| Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (a || b) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(a && b) is false.
not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. not(a && b) is false.

Ruby三元運算符:

還有一個運算符稱為三元運算符。這首先計算一個表達式為true或false值,然後執行一個計算結果來決定兩個語句的哪一個。條件運算符的語法如下:

運算符 描述 例子
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y

Ruby範圍運算符:

Ruby中的序列範圍是用來創建連續值 - 組成了開始值/結束值,並在兩者之間的值的範圍內。

在Ruby中,創建這些序列使用“..”和“...”範圍運算符。這兩個點的形式建立一個包容性的範圍,而三個點的形式創建了一個範圍,不包括指定的最大值。

運算符 描述 例子
.. Creates a range from start yiibai to end yiibai inclusive 1..10 Creates a range from 1 to 10 inclusive
... Creates a range from start yiibai to end yiibai exclusive 1...10 Creates a range from 1 to 9

Ruby defined? 操作符:

defined? 是一個特殊的操作符采取的形式的方法調用,以確定是否通過表達式定義。如果冇有被定義的表達式,它返回一個描述字符串求解出的表達式或nil

有很多種用法 defined? 操作符:

用法 1

defined? variable # True if variable is initialized

例如 :

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

用法 2

defined? method_call # True if a method is defined

例如 :

defined? puts        # => "method"
defined? puts(bar)   # => nil (bar is not defined here)
defined? unpack      # => nil (not defined here)

用法 3

# True if a method exists that can be called with super user
defined? super

例如 :

defined? super     # => "super" (if it can be called)
defined? super     # => nil (if it cannot be)

用法 4

defined? yield   # True if a code block has been passed

例如 :

defined? yield    # => "yield" (if there is a block passed)
defined? yield    # => nil (if there is no block)

Ruby "." 雙冒號 "::" 運算符:

調用一個模塊方法,通過模塊的名稱和句點它的名字前,引用一個常數使用該模塊的名稱和兩個冒號。
::使得一元運算符,常數,實例方法和類方法在類或模塊定義,從任何地方訪問外的類或模塊。
請記住:在Ruby中,類和方法可以被視為常數。隻需要前綴::Const_name的表達式返回相應的類或模塊對象。
如果冇有前綴表達式時,主要對象類默認情況下使用。
這裡有兩個例子:

MR_COUNT = 0        # constant defined on main Object class
module Foo
  MR_COUNT = 0
  ::MR_COUNT = 1    # set global count to 1
  MR_COUNT = 2      # set local count to 2
end
puts MR_COUNT       # this is the global constant
puts Foo::MR_COUNT  # this is the local "Foo" constant

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運算符優先級

下表列出了所有運算符從最高優先級到最低。

方法 運算符 描述
Yes :: Constant resolution operator
Yes [ ] [ ]= Element reference, element set
Yes ** Exponentiation (raise to the power)
Yes ! ~ + - Not, complement, unary plus and minus (method names for the last two are +@ and -@)
Yes * / % Multiply, divide, and modulo
Yes + - Addition and subtraction
Yes >> << Right and left bitwise shift
Yes & Bitwise 'AND'
Yes ^ | Bitwise exclusive `OR' and regular `OR'
Yes <= < > >= Comparison operators
Yes <=> == === != =~ !~ Equality and pattern match operators (!= and !~ may not be defined as methods)
  && Logical 'AND'
  || Logical 'OR'
  .. ... Range (inclusive and exclusive)
  ? : Ternary if-then-else
  = %= { /= -= += |= &= >>= <<= *= &&= ||= **= Assignment
  defined? Check if specified symbol defined
  not Logical negation
  or and Logical composition

注: 方法列一個是運算符實際上是方法,因此可能會被改寫。