写的一个inter类模仿ruby整数的行为

简介:

我们知道ruby中对于整数的[],[]=,<<,>>操作是针对于二进制的值来运算的。

我现在写一个针对十进制数操作的类,拥有整数的所有方法,如下:

 

class InterEx def initialize(val=0) @val=val end def to_s @val.to_s end def [](idx) self.to_s[idx].to_i end def []=(idx,val) s=self.to_s s[idx] = val.to_s @val=s.to_i end def coerce(other) [other,@val] end def <<(v) return InterEx.new(@val) if v==0 InterEx.new(@val*10**v) end def >>(v) return InterEx.new(@val) if v==0 s=self.to_s s=s[0..(-1*v-1)] InterEx.new(s.to_i) end def method_missing(mtd,*args) InterEx.new(@val.send mtd,*args) end end

 

ruby还提供了delegate机制便于代理一个类,比如要想代理Fixnum类,

可以这么写:

 

require 'delegate' class InterEx<DelegateClass(Fixnum) ... end

 

相关文章
|
3月前
|
Ruby
|
3月前
|
Ruby
|
3月前
|
Ruby
|
3月前
|
Ruby
|
4月前
|
Ruby
|
4月前
|
Ruby
|
4月前
|
Ruby
|
4月前
|
Ruby
|
7月前
|
Ruby
一些奇怪的 Ruby 行为
一些奇怪的 Ruby 行为
|
Java 程序员 数据安全/隐私保护
【Ruby高级技术】对面向对象里的控制访问,包括类的继承类常量的深入理解和使用
【Ruby高级技术】对面向对象里的控制访问,包括类的继承类常量的深入理解和使用