查看RMXP幫助手冊,我們會發現這個類里有如下屬性(Attributes):

這個類共有11個屬性。
現在我們嫌一個個地寫太麻煩,想用一個循環語句自動遍歷這11個屬性。
先看這個類的定義:

目前共有11篇帖子。
![]() |
我們以RPG Maker XP里自帶的RPG::Map類為例。
查看RMXP幫助手冊,我們會發現這個類里有如下屬性(Attributes): ![]() 這個類共有11個屬性。 現在我們嫌一個個地寫太麻煩,想用一個循環語句自動遍歷這11個屬性。 先看這個類的定義: ![]() |
![]() |
【代碼】
map = load_data("Data/Map001.rxdata") for varName in map.instance_variables p map.instance_variable_get(varName) end 【講解】 首先,第一行是從文件Data/Map001.rxdata中載入對象,並保存到map變量中,這個對象是RPG::Map類的一個實例。 現在,如果執行p map.width(1號地圖的寬度),就能把這個對象的width屬性的值輸出出來。 但是如果這11個屬性都一一這麼寫會比較麻煩,於是通過map.instance_variables獲取所有的這11個類屬性的名稱,並作循環。在循環體裏通過map.instance_variable_get(varName)這條語句間接讀取這個對象的各個屬性。 |
![]() |
執行
p map.width 輸出20,正好是一號地圖的寬度。 這條語句還可以改寫成: p map.instance_variable_get("@width") 同樣也是輸出20 當然,還有另外兩種方法: p map.width() p map.method("width").call 也就是把width屬性當做方法來調用,返回的就是這個屬性的值。 |
![]() |
如果我們執行
p map.method("width").arity 返回的值為0,也就是說width這個「方法」,參數個數為0 |
![]() |
【補充】
p map.methods() 返回該對象的所有屬性名和方法名構成的數組,屬性名前不帶「@」字符。 輸出結果: ![]() |
![]() |
p map.instance_variables()
返回該對象的所有屬性名構成的數組,屬性名前帶有「@」字符。 輸出結果: ![]() |
![]() |
def map.hello()
p "Hello World" end p map.singleton_methods() 返回用戶對該對象變量單獨定義的方法。 輸出結果: ![]() 參考資料: A method given only to a single object is called a singleton method. http://www.rubyist.net/~slagell/ruby/singletonmethods.html 這篇文章詳細的介紹了什麼是Singleton Method。 |
![]() |
map.method("方法名").arity
獲取這個對象中的一個方法接受的參數個數 map.method("方法名").call(...) 調用這個方法 例如: def map.hello(firstname, lastname) print "Hello World, " + firstname + " " + lastname end print "參數個數為:" + map.method("hello").arity.to_s map.method("hello").call("Zig", "Zag") 輸出結果: ![]() ![]() |
![]() |
map.method("方法名")返回一個Method對象,關於Method類的介紹請參閱Ruby的官方文檔:
http://ruby-doc.org/core-2.2.3/Method.html 要查看這個Method對象里有哪些方法,請執行: p map.method("方法名").methods |
![]() |