Ruby支援一系列豐富的運算子的一個現代化的語言。大多數運算子實際上是方法調用。例如,a + b的被解釋為a,
+(b)變數引用的對象的方法被稱為一個用b作為它的參數。
對於每個運算子 (+ - * / % ** & | ^ << >> && ||), 有相應的賦值運算子縮寫形式 (+= -= 等)
Ruby算術運算子:
假設變數a=10,變數b=20:
Ruby比較操作符:
假設變數a=10,變數b=20:
Ruby賦值運算子:
假設變數a=10,變數b=20:
Ruby並行賦值:
Ruby還支援並行賦值的變數。這使得多個一行Ruby代碼來初始設定變數。例如:
需要更迅速聲明,使用並行賦值:
並行賦值交換兩個變數的值也是有用的:
Ruby位元運算符:
位元運算符位和位操作執行位。
假設當a =60和b=13;現在以二進位格式將如下:
a = 0011 1100b = 0000 1101-----------------a&b = 0000 1100a|b = 0011 1101a^b = 0011 0001~a = 1100 0011
支援Ruby語言的位元運算符
Ruby邏輯運算子:
支援Ruby語言的邏輯運算子
假設變數a=10,變數b=20:
Ruby三元運算子:
還有一個運算子稱為三元運算子。這首先計算一個運算式為true或false值,然後執行一個計算結果來決定兩個語句的哪一個。條件運算子的文法如下:
Ruby範圍運算子:
Ruby中的序列範圍是用來建立連續值 - 組成了開始值/結束值,並在兩者之間的值的範圍內。
在Ruby中,建立這些序列使用“..”和“...”範圍運算子。這兩個點的形式建立一個包容性的範圍,而三個點的形式建立了一個範圍,不包括指定的最大值。
Ruby defined? 操作符:
defined是一個特殊的操作符採取的形式的方法調用,以確定是否通過運算式定義。如果沒有被定義的運算式,它返回一個描述字串求解出的運算式或nil
有很多種用法 defined操作符:
用法 1
defined? variable # True if variable is initialized
例如 :
foo = 42defined? 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 userdefined? 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 classmodule Foo MR_COUNT = 0 ::MR_COUNT = 1 # set global count to 1 MR_COUNT = 2 # set local count to 2endputs MR_COUNT # this is the global constantputs Foo::MR_COUNT # this is the local "Foo" constantSecond Example:CONST = ' out there'class Inside_one CONST = proc {' in there'} def where_is_my_CONST ::CONST + ' inside one' endendclass Inside_two CONST = ' inside two' def where_is_my_CONST CONST endendputs Inside_one.new.where_is_my_CONSTputs Inside_two.new.where_is_my_CONSTputs Object::CONST + Inside_two::CONSTputs Inside_two::CONST + CONSTputs Inside_one::CONSTputs Inside_one::CONST.call + Inside_two::CONST
Ruby運算子優先順序
下表列出了所有運算子從最高優先順序到最低。
注: 方法列一個是運算子實際上是方法,因此可能會被改寫。