Ruby支持一系列豐富的運算符的一個現代化的語言。大多數運算符實際上是方法調用。例如,a + b的被解釋為a,
+(b)變量引用的對象的方法被稱為一個用b作為它的參數。
對于每個運算符 (+ - * / % ** & | ^ << >> && ||), 有相應的賦值運算符縮寫形式 (+= -= 等)
Ruby算術運算符:
假設變量a=10,變量b=20:
Ruby比較操作符:
假設變量a=10,變量b=20:
Ruby賦值運算符:
假設變量a=10,變量b=20:
Ruby并行賦值:
Ruby還支持并行賦值的變量。這使得多個一行Ruby代碼來初始化變量。例如:
a = 10b = 20c = 30
需要更迅速聲明,使用并行賦值:
a, b, c = 10, 20, 30
并行賦值交換兩個變量的值也是有用的:
a, b = b, c
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運算符優先級
下表列出了所有運算符從最高優先級到最低。
注: 方法列一個是運算符實際上是方法,因此可能會被改寫。
新聞熱點
疑難解答
圖片精選