在ruby中对Fixnum进行子类化 [英] Sub-classing Fixnum in ruby
问题描述
所以我理解你不应该直接将Fixnum,Float或Integer子类化,因为它们没有#new方法。使用DelegateClass似乎工作,但它是最好的方法吗?有谁知道这些类没有#new背后的原因是什么?
So I understand you aren't supposed to to directly subclass Fixnum, Float or Integer, as they don't have a #new method. Using DelegateClass seems to work though, but is it the best way? Anyone know what the reason behind these classes not having #new is?
我需要一个类似Fixnum的类,但有一些额外的方法,我想要能够通过类中的 self
引用其值,例如:
I need a class which behaves like a Fixnum, but has some extra methods, and I'd like to be able to refer to its value through self
from within the class, for example:
class Foo < Fixnum
def initialize value
super value
end
def increment
self + 1
end
end
Foo.new(5).increment + 4 # => 10
推荐答案
您可以非常轻松地设置快速转发实施你自己:
You can pretty easily set up a quick forwarding implementation yourself:
class MyNum
def initialize(number)
@number = number
end
def method_missing(name, *args, &blk)
ret = @number.send(name, *args, &blk)
ret.is_a?(Numeric) ? MyNum.new(ret) : ret
end
end
然后你可以在MyNum上添加你想要的任何方法,但是你需要在这些方法中使用@number,而不是直接调用super。
Then you can add whatever methods you want on MyNum, but you'll need to operate on @number in those methods, rather than being able to call super directly.
这篇关于在ruby中对Fixnum进行子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!