ThoML
2/12/2008 9:26:00 PM
> > 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. 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__]
Regards,
Thomas.