本文簡要介紹ruby語言中 Class類 的用法。
擴展任何 Class 以包含 json_creatable? 方法。
Ruby 中的類是 first-class 對象——每個都是類 Class 的一個實例。
通常,您可以使用以下方法創建一個新類:
class Name
# some code describing the class behavior
end
當一個新類被創建時, Class 類型的對象被初始化並分配給一個全局常量(在本例中為名稱)。
當調用Name.new創建新對象時,默認運行 Class 中的 new 方法。這可以通過在 Class 中覆蓋 new 來證明:
class Class
alias old_new new
def new(*args)
print "Creating a new ", self.name, "\n"
old_new(*args)
end
end
class Name
end
n = Name.new
產生:
Creating a new Name
類、模塊和對象是相互關聯的。在下圖中,垂直箭頭表示繼承,括號表示元類。所有元類都是類“類”的實例。
+---------+ +-...
| | |
BasicObject-----|-->(BasicObject)-------|-...
^ | ^ |
| | | |
Object---------|----->(Object)---------|-...
^ | ^ |
| | | |
+-------+ | +--------+ |
| | | | | |
| Module-|---------|--->(Module)-|-...
| ^ | | ^ |
| | | | | |
| Class-|---------|---->(Class)-|-...
| ^ | | ^ |
| +---+ | +----+
| |
obj--->OtherClass---------->(OtherClass)-----------...
相關用法
- Ruby Class.superclass用法及代碼示例
- Ruby Class.inherited用法及代碼示例
- Ruby Class.new用法及代碼示例
- Ruby Class.allocate用法及代碼示例
- Ruby Class.file用法及代碼示例
- Ruby Class.subclasses用法及代碼示例
- Ruby Closure類用法及代碼示例
- Ruby ClosedError類用法及代碼示例
- Ruby CStructEntity.[]=用法及代碼示例
- Ruby Context.save_history=用法及代碼示例
- Ruby CSV.header_convert用法及代碼示例
- Ruby Constants模塊用法及代碼示例
- Ruby CMath tanh()用法及代碼示例
- Ruby CSV.skip_lines用法及代碼示例
- Ruby CGI.new用法及代碼示例
- Ruby Comparable.between?用法及代碼示例
- Ruby CGI.print用法及代碼示例
- Ruby CGI.http_header用法及代碼示例
- Ruby CMath cos()用法及代碼示例
- Ruby Complex.arg用法及代碼示例
- Ruby CSV.table用法及代碼示例
- Ruby CSV.force_quotes?用法及代碼示例
- Ruby CParser模塊用法及代碼示例
- Ruby CSV.unconverted_fields?用法及代碼示例
- Ruby ComposedSet類用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Class類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
