How can I duplicate class inheriting Array with keeping it's type?

Hello.
I have trouble in duplicationg class inheriting Array. Here is a sample code.

class Foo; end

class Bar < Array(Foo)
end

bar = Bar.new
bar2 = bar.dup
puts typeof(bar2) # => Array(Foo)

bar2’s type becomes Array(Foo). I know it’s natural because bar.dup calls Array#dup.
But, I want bar2’s type to be Bar.
Are there any solution to duplicate and keep it’s type Bar ?

Thanks.

I would advise against inheriting any of the stdlib’s primitive types, such as Array, or Hash, etc.

A better option would be to use a decorator, e.g.

class Foo; end

class Bar
  forward_missing_to @array

  def initialize(@array : Array(Foo)); end
end

Alternatively, depending more on your use case, an alias might make more sense?

alias Bar = Array(Foo)

I do remember seeing an issue about this however. I’ll see if i can find it.

EDIT: I can’t

2 Likes

I would advise against inheriting any of the stdlib’s primitive types

I see. When I ran into this problem, I felt the way of inheriting Array may be not good.
Now, I’m going to take first approach, letting Bar have Array instance and delegate certain method to it.

Thank you!