-3

Below there is a code that works:

class LikeAnArray < Array

end

If I run:

$ p object = LikeAnArray.new

It returns:

$ #=> []

If I run:

$ p object.class

It returns:

$ #=> LikeAnArray

How can I achieve this functionality without making my class be a sub class of Array?

Sean
  • 983
  • 5
  • 13
rplaurindo
  • 1,277
  • 14
  • 23
  • I think p and puts call to_s automatically. if you want your output to look like an array override the to_s method in your class. additionally still need to implement enumerable on your data at some point so why not just inherit from array? – Carlos Roque Oct 25 '17 at 19:31
  • Thanks, but I should overwrite [```inspect```](https://ruby-doc.org/core-2.4.2/Object.html#method-i-inspect) as can be seen [here](https://ruby-doc.org/core-2.4.2/Kernel.html#method-i-p), in really. – rplaurindo Oct 25 '17 at 19:39

1 Answers1

1

With class LikeArray < Array; end you can achieve the behaviour you are looking for. What are you trying to do?

cmramseyer
  • 447
  • 2
  • 7
  • Thanks. I like how the ```ActiveRecord``` gem works. More specifically the ```Relation``` class, it returns an object with the format ```[..., ..., ...]```, but it doesn't inherits from ```Array```. – rplaurindo Oct 24 '17 at 16:11
  • See: https://stackoverflow.com/questions/7220634/how-do-i-use-the-enumerable-mixin-in-my-class – 3limin4t0r Oct 27 '17 at 08:56