本文简要介绍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类。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
