定义一个适用于特定类型对象的数组的方法
在 C# 中,您可以编写如下扩展方法:
public static Debt[] Foo(this Debt[] arr, int num)
{
// Do something
}
这将允许您对债务数组使用 Foo()
:debts.Foo(3)
您可以这样做吗在鲁比?我知道你可以编写一个适用于数组的方法:
class Array
def foo
# blah
end
end
但这适用于所有类型的数组,而不仅仅是债务数组。
提前致谢。
In C# you can write an extension method like this:
public static Debt[] Foo(this Debt[] arr, int num)
{
// Do something
}
This would allow you to use Foo()
on an array of debts: debts.Foo(3)
Can you do this in Ruby? I know you can write a method that will work on arrays:
class Array
def foo
# blah
end
end
but this works on all types of arrays, not just an array of Debt
s
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
extend
方法将实例方法添加到特定对象。所以在你的情况下它会是:实际上它为债务对象创建单例类,然后向其添加方法。但是你不能使用这个类,这就是为什么它被称为“幽灵”类
the
extend
method is adding the instance methods to a particular object. so in you case it would be:Actually it creates singleton class for
debts
object and then add to it the method. But you can't use this class, that's why it called "ghost" class这会有点棘手,因为 Ruby 数组不是同类的。也就是说,您可以在数组中存储不同类型的对象。这将引导我找到一个解决方案,我需要首先验证数组中的所有对象是否都是 Debt 类型,如果是,那么我可以使用 foo 对数组进行操作>。
您可以继续打开
Array
并添加foo
方法,但也许您应该创建一个FooArray
并扩展Array.这样您就可以重新定义一些方法,例如
<<
和push
以确保您只获取Debt
。由于您知道只有Debt
可以添加到数组中,因此您可以放心调用foo()
。This would be a little tricky because Ruby arrays are not homogeneous. That is, you can store different types of objects inside of an array. That would lead me to a solution where I need to first verify that all objects in the array are of type
Debt
, and if they are then I can act on the array usingfoo
.You can continue to open up
Array
and add thefoo
method, but maybe you should create aFooArray
instead and extendArray
. This way you can redefine some methods such as<<
andpush
to ensure you only takeDebt
s. Since you know that onlyDebt
s can be added to your array, you could callfoo()
without worry.我相信您可以通过扩展 Ruby 的 Array 类或更好地定义您自己的类似 Array 的类并将选定的数组方法委托给本机对象来实现此目的。
为什么这比其他方法更好此处解释。
I believe you can do this by extending Ruby's Array class or better yet defining your own Array-like class and delegating the selected array methods to the native object.
Why this is better than the alternative methods is explained here.