3

I am creating a wrapper class for Ruby's NArray (numeric array). I would like my class to respond to all of the standard mathematical operators (+, +=, -, -=, *, *=, etc) in the same way that an instance of NArray does. I know how to make wrappers for Arrays and other Enumerable objects, include Enumerable in the wrapper, and define an each method that just redirects to the wrapped Enumerable object. I would like something similar with the NArray. Is there a single module to include/method I can define that will define the whole bevy of mathematical operators to target the wrapped NArray? Or do I have to define them all manually?

4

1 回答 1

2

You could use Forwardable:

require 'forwardable'
class MyWrapper

  extend Forwardable
  def_delegators :@narray, :+, :*, # etc...

  def initialize(narray)
    @narray = narray
  end
end

I'm not sure this will work with the += et al methods (I don't know exactly how they are implemented, but I believe they are a feature of the parser and not actually methods you can reference).

Calling += on an instance of MyWrapper would set the reference to the result of that operation, so you would need to figure out a way for that to return the same instance. That raises the question - is that what you want to do (return a wrapped NArray as the result of mathematical operations), or do you expect your NArray to handle the returns?

于 2012-11-04T01:04:55.840 回答