From: Rick DeNatale Date: 2008-02-13T06:41:52+09:00 Subject: Re: Subclassing Integer; solved! On 2/12/08, ThoML wrote: > > > Year.new(2008).class # => Fixnum > > > Year.new(2008) == 2008 # => true > > > > That's exactly what I want. > > The latter gives false with ruby19 though. Also it seems impossible to > define a method in Year. > > class Year < Integer > def foo > self * 2000 > end > end > Year.new(2008).foo > # NoMethodError: undefined method `foo' for 2008:Fixnum > > Also, I don't quite understand the hack with inherited() since it > doesn't do anything. The reason why the class() method returns > 'Fixnum' is not because of the inheritance but because of > #method_missing. Well you really can define a method in Year, it's just that Year.new doesn't return an instance of Year, it returns an instance of BoxedInteger (not Fixnum as I had said earlier.) > A IMHO slightly more accessible/"traditional" way to > achieve the same would be: > > class Year < BasicObject > def initialize(value) > @value = value > end > > def foo > @value * 2000 > end > > def ==(other) > @value == other > end > > def respond_to? > @value.respond_to? > end > > private > def method_missing(meth, *args, &block) > @value.send meth, *args, &block > end > end > > Year.new(2008).class > # => Fixnum > Year.new(2008).foo > # => 4016000 > Year.new(2008) == 2008 > # => true > Year.new(2008).class.superclass > # => Integer > > If you define #method_missing, you'll also have to define respond_to?. > It seems also necessary to define #== and a few other methods: > > irb(main):001:0> BasicObject.instance_methods > => [:==, :equal?, :"!", :"!=", :__send__] Or just use Delegator. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/