Ruby 元编程 类定义
来源:互联网 发布:js 点击复制当前内容 编辑:程序博客网 时间:2024/04/30 06:45
1.类实例变量
- 2.0.0p247 :342 > class MyClass
- 2.0.0p247 :343?> @my_var = 1
- 2.0.0p247 :344?> def self.read
- 2.0.0p247 :345?> @my_var
- 2.0.0p247 :346?> end
- 2.0.0p247 :347?>
- 2.0.0p247 :348 > def write; @my_var = 2; end
- 2.0.0p247 :349?> def read; @my_var;end
- 2.0.0p247 :351?> end
类变量
class C
@@v = 1
end
2.单件方法
- 2.0.0p247 :319 > str = "any string paragraph"
- => "any string paragraph"
- 2.0.0p247 :320 > def str.title?
- 2.0.0p247 :321?> self.upcase == self
- 2.0.0p247 :322?> end
- => nil
- 2.0.0p247 :323 > str
- => "any string paragraph"
- 2.0.0p247 :324 > str.title?
- => false
- 2.0.0p247 :325 >
3.类方法 和 单件方法其实是一样的
4.类宏
- 2.0.0p247 :362 > class MyClass
- 2.0.0p247 :363?> attr_accessor :my_atttribute
- 2.0.0p247 :364?> end
5.eigenclass 单件类
- 2.0.0p247 :380 > class Object
- 2.0.0p247 :381?> def
- 2.0.0p247 :382 > eigenclass
- 2.0.0p247 :383?> class < self; self; end
- 2.0.0p247 :384?> end
- SyntaxError: (irb):383: syntax error, unexpected '<'
- class < self; self; end
- ^
- from /Users/menxu/.rvm/rubies/ruby-2.0.0-p247/bin/irb:16:in `<main>'
- 2.0.0p247 :385 > class Object
- 2.0.0p247 :386?> def eigenclass
- 2.0.0p247 :387?> class << self;self ; end
- 2.0.0p247 :388?> end
- 2.0.0p247 :389?> end
- => nil
- 2.0.0p247 :390 > "abc".eigenclass
- => #<Class:#<String:0x007fdaea9fdb30>>
- 2.0.0p247 :391 > obj = Object.new
- => #<Object:0x007fdaea9eee78>
- 2.0.0p247 :392 > class << obj
- 2.0.0p247 :393?> def a_singleton_method
- 2.0.0p247 :394?> "obj#a_singleton_method()"
- 2.0.0p247 :395?> end
- 2.0.0p247 :396?> end
- => nil
- 2.0.0p247 :397 > obj.eigenclass
- => #<Class:#<Object:0x007fdaea9eee78>>
- 2.0.0p247 :398 > obj.eigenclass.superclass
- => Object
- 2.0.0p247 :399 > obj.a_singleton_method
- => "obj#a_singleton_method()"
- 2.0.0p247 :400 >
6.方法别名 alias
- 2.0.0p247 :412 > ob = MyAlias.new
- => #<MyAlias:0x007fdaea94e950>
- 2.0.0p247 :413 > ob.my_method
- => "my_method()"
- 2.0.0p247 :414 > ob.m
- => "my_method()"
- 2.0.0p247 :415 >
- 2.0.0p247 :416 >
0 0
- Ruby 元编程 类定义
- Ruby 元编程 类定义
- ruby元编程——类定义
- Ruby元编程-学习笔记(四)-类定义
- Ruby元编程-学习笔记(四)-类定义
- ruby元编程4------类
- Ruby 元编程 类的真相
- Ruby 元编程 类的真相
- ruby元编程
- ruby元编程记录
- Ruby 元编程 方法
- Ruby 元编程
- 《ruby 元编程》读书笔记
- 读《Ruby 元编程》
- Ruby 元编程 方法
- ruby元编程读后感
- 《Ruby 元编程》笔记
- Ruby元编程
- Linux内核源代码情景分析-基于socket的进程间通信
- Spring学习笔记(6)---------IoC的三种注入方式
- 深入理解alias, alias_method和alias_method_chain
- Ruby 元编程 编写代码的代码
- 【CF】Codeforces Round #301 (Div. 2) ABCDE
- Ruby 元编程 类定义
- 又一版 A+B(1877)
- 银行理财产品未登记不可售
- Ruby 元编程 代码块
- Ruby 元编程 方法
- [iOS进阶]iOS缓存机制详解
- Ruby 元编程 类的真相
- 2 - 1.1 = 0.8999999999999999
- 用USB 安装linux