to_na instance method
After subclassing NArray, I have discovered that NArray is missing a similar feature compared to Ruby's Array where you easily convert back to an Array.
With Array I can do this:
a = Array.new(3)
=> [nil, nil, nil]
a.class
=> Array
a.to_a.class
=> Array
class M < Array
end
=> nil
m = M.new(3)
=> [nil, nil, nil]
m.class
=> M
m.to_a.class
=> Array
I propose we add a to_na instance method to NArray, similar as the to_a instance method for Array. The documentation for Ruby's to_a method says:
- Returns self. If called on a subclass of Array, converts the receiver to an Array object.
We can then do:
n = NArray.new(1,3)
=> NArray.byte(3):
[ 0, 0, 0 ]
n.class
=> NArray
n.to_na.class
=> NArray
class C < NArray
end
=> nil
c = C.new(1,3)
=> C.byte(3):
[ 0, 0, 0 ]
c.class
=> C
c.to_na.class
=> NArray
Is this possible?
- I think the non-standard NArray class is in a different position from the build-in Array class.
- If NArray provides Array#to_a and another library, e.g., NextArray, brings also Array#to_na, you cannot use NextArray and NArray simultaneously.
Perhaps you misunderstood me. I'm not proposing we touch Array class.
My proposal is we modify NArray class so that it behaves like Array when it is subclassed, by adding a to_na instance method to NArray.
I want to be able to do this with NArray:
n = NArray.new(1,3)
n.to_na.class
=> NArray
class C < NArray
end
c = C.new(1,3)
c.class
=> C
c.to_na.class
=> NArray
OK, now perhaps I understand.
But it seems to me that to_na does not well express your intent.
Instead, how about NArray.cast method?
class C < NArray; end
n = NArray[1..3]
=> NArray.int(3):
[ 1, 2, 3 ]
C.cast(n)
=> C.int(3):
[ 1, 2, 3 ]
C.cast(n,NArray::DFLOAT)
=> C.float(3):
[ 1.0, 2.0, 3.0 ]
c = C.new(1,3,2)
=> C.byte(3,2):
[ [ 0, 0, 0 ],
[ 0, 0, 0 ] ]
NArray.cast(c)
=> NArray.byte(3,2):
[ [ 0, 0, 0 ],
[ 0, 0, 0 ] ]
NArray.cast(c,Float)
=> NArray.float(3,2):
[ [ 0.0, 0.0, 0.0 ],
[ 0.0, 0.0, 0.0 ] ]
a = [[1,2],[3,4]]
=> [[1, 2], [3, 4]]
NArray.cast(a)
=> NArray.int(2,2):
[ [ 1, 2 ],
[ 3, 4 ] ]
NArray.cast(a,NArray::DFLOAT)
=> NArray.float(2,2):
[ [ 1.0, 2.0 ],
[ 3.0, 4.0 ] ]
Diff patch: https://github.com/masa16/narray/commit/b64f096039728b2c93d66f7f15e72cf8ca5691b7