初學RUBY時,一看各種稍微復雜一點的代碼時很容易被RUBY各種約定的表示方法搞暈,這整理一下 。
(若標識符首位是小寫字母或“_”,則該標識符就是局部變量或方法調用。)
(以大寫字母([A-Z])開始的標識符是常數、類名或者模塊名)
以@開始的變量是實例變量,它屬於特定的對象。可以在類或子類的方法中引用實例變量。
若引用尚未被初始化的實例變量的話,其值為nil。Ruby的實例變量無須聲明,每個實例變量都是在第一次出現時動態加入對象。Ruby的實例變量通常在方法中定義類聲明——當在方法里聲明實例變量時,該實例變量實際上屬於該方法所在類的實例,而不是屬於該方法。例如
class Apple # 定義第一個方法 def info1 # 輸出實例變量@a puts @a end # 定義第二個方法 def info2 # 為實例變量賦值 @a = "Hello"; end end # 創建Apple類實例 apple = Apple.new # 調用方法 apple.info2 apple.info1
以@@開始的變量是類變量。在類的定義中定義類變量,可以在類的特殊方法、實例方法等處對類變量進行引用/賦值:
class Foo @@foo = 1 def bar puts @@foo end end
類變量與常數的區別如下。
- 可以重復賦值(常數則會發出警告)
- 不能在類的外部直接引用(在繼承類中則可以引用/賦值)
類變量與類的實例變量的區別如下。
- 可在子類中引用/賦值
- 可在實例方法中引用/賦值
可以把類變量看作一種被類、子類以及它們的實例所共享的全局變量。
class Foo @@foo = 1 end class Bar < Foo p @@foo += 1 # => 2 end class Baz < Bar p @@foo += 1 # => 3 end
模塊中定義的類變量(模塊變量)被所有包含該模塊的類所共享。
module Foo @@foo = 1 end class Bar include Foo p @@foo += 1 # => 2 end class Baz include Foo p @@foo += 1 # => 3 end
以$開始的變量是全局變量,可以在程序的任何地方加以引用(因此需要特別留意)。全局變量無需變量聲明。引用尚未初始化的全局變量時,其值為 nil。
%表示法(百分號表示法):
%{String} 用於創建一個使用雙引號括起來的字符串
%Q{String} 用於創建一個使用雙引號括起來的字符串
%q{String} 用於創建一個使用單引號括起來的字符串
%r{String} 用於創建一個正則表達式字面值
%w{String} 用於將一個字符串以空白字符切分成一個字符串數組,進行較少替換
%W{String} 用於將一個字符串以空白字符切分成一個字符串數組,進行較多替換
%s{String} 用於生成一個符號對象
%x{String} 用於執行String所代表的命令
"%05d" % 123 » "00123"
"%-5s: %08x" % [ "ID", self.id ] » "ID:200e1670"
# 用來調用一個方法,
*號:
若左邊最后一個表達式前帶*的話,則將右邊多余的元素以數組的形式代入這個帶*的表達式中。若右邊沒有多余元素的話,就把空數組代入其中。
*foo = 1, 2, 3 # foo = [1, 2, 3] foo,*bar = 1, 2, 3 # foo = 1; bar = [2, 3]
*用在方法定義中表示可變長的變量:
【FROM “ProgrammingRuby”】
Variable-Length Argument Lists
But what if you want to pass in a variable number of arguments, or want to capture multiple arguments into a single parameter? Placing an asterisk before the name of the parameter after the ``normal'' parameters does just that.
def varargs(arg1, *rest) "Got #{arg1} and #{rest.join(', ')}" end varargs("one") » "Got one and " varargs("one", "two") » "Got one and two" varargs "one", "two", "three" » "Got one and two, three"
irb(main):005:0> def call_back(*a) irb(main):006:1> a.each do |arg| irb(main):007:2* puts arg irb(main):008:2> end irb(main):009:1> end => nil irb(main):011:0> call_back(["hello",99]) hello 99 => [["hello", 99]] irb(main):012:0> call_back(["hello",99],"hello",99) hello 99 hello 99 => [["hello", 99], "hello", 99]
其他用法:
C:\Users\Administrator>irb
irb(main):001:0> [1,2,3] * "hi"
=> "1hi2hi3"
irb(main):002:0> [1,2,3] * ";"
=> "1;2;3"
irb(main):003:0> [1,2,3] * 3
=> [1, 2, 3, 1, 2, 3, 1, 2, 3]
irb(main):004:0> "hi" * 3
=> "hihihi"