Ruby語言基礎學習三 Ruby變數 運算

2021-07-10 22:20:09 字數 1838 閱讀 5397

#_*_ coding:utf-8 _*_

# 聯合比較運算子。如果第乙個運算元等於第二個運算元則返回 0,

# 如果第乙個運算元大於第二個運算元則返回 1,如果第乙個運算元小於第二個運算元則返回 -1。

a=10

b=12

c=10<=>12

puts c

a1,b1,c1=10,20,30

a,b=b,a;#這樣設計很巧妙,可以直接進行兩個東西的值進行對調

puts a,b

#位運算

a2 = 0b0011

b2 = 0b0000

a2&b2#交集

a2|b2#並集

a2^b2#異或

~a2 #非

#defined? 是乙個特殊的運算子,以方法呼叫的形式來判斷傳遞的表示式是否已定義。

#它返回表示式的描述字串,如果表示式未定義則返回 nil。

#用法一:defined? variable # 如果 variable 已經初始化,則為 true

foo = 42

defined? foo # => "local-variable"

defined? $_ # => "global-variable"

defined? bar # => nil(未定義)

#用法二:defined? method_call # 如果方法已經定義,則為 true

defined? puts # => "method"

defined? puts(bar) # => nil(在這裡 bar 未定義)

defined? unpack # => nil(在這裡未定義)

# 用法三:如果存在可被 super 使用者呼叫的方法,則為 true

#defined? super

defined? super # => "super"(如果可被呼叫)

defined? super # => nil(如果不可被呼叫)

#用法四:defined? yield # 如果已傳遞**塊,則為 true

defined? yield # => "yield"(如果已傳遞塊)

defined? yield # => nil(如果未傳遞塊)

# ruby 點運算子 "." 和雙冒號運算子 "::"

# 請記住:在 ruby 中,類和方法也可以被當作常量。

const = ' out there' #全域性變數

class inside_one

const = proc #定義的是區域性變數

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_const #這個方式比較特殊

puts inside_two.new.where_is_my_const

puts object::const + inside_two::const #取例項的變數

puts inside_two::const + const #在這裡不說明的是全域性變數

puts inside_one::const.call #這裡要加上call才能正確顯示,因為有proc

puts inside_one::const.call + inside_two::const

Ruby語言基礎

ruby中除了false以外,其餘所有物件中只有nil能代表為空,幾遍是數字0也表示true if nil nil is true else nil is false endif 0 0 is true else 0 is false end陣列 有多種方法呼叫 a w a.shuffle 打亂順序...

ruby學習之語言基礎

檔案字尾名.rb 1.輸出語法 puts hello,ruby prints hello,world 將內容儲存為a.rb 並將此檔案放入目錄d盤下的ror目錄中 執行命令d ror ruby a.rb 就會看到輸出 hello,ruby hello,world 2.換行 puts zhangsan...

Ruby語言基礎學習九 Ruby範圍 迭代器

範圍,本文參考 作為序列的範圍 ruby 使用 和 範圍運算子建立這些序列。兩點形式建立乙個包含指定的最高值的範圍,三點形式建立乙個不包含指定的最高值的範圍。array 值分隔符 range1 1.10 to a 轉換成陣列 range2 a d to a range3 bar bat to a p...