Define a method that works on arrays of a specific type of object
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
#开发者_Python百科 blah
end
end
but this works on all types of arrays, not just an array of Debt
s
Thanks in advance.
the extend
method is adding the instance methods to a particular object. so in you case it would be:
class YourClass
def foo
# blah
end
end
debts.extend(YourClass)
debts.foo # now foo method is instance method of debts object
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
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 using foo
.
You can continue to open up Array
and add the foo
method, but maybe you should create a FooArray
instead and extend Array
. This way you can redefine some methods such as <<
and push
to ensure you only take Debt
s. Since you know that only Debt
s can be added to your array, you could call foo()
without worry.
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.
Stack = Array.extract([
:last,
:push,
:pop,
:size,
:clear,
:inspect,
:to_s
])
Why this is better than the alternative methods is explained here.
精彩评论