What should I implement for the user class to behave exactly like an array?

Say I have my own class, what should I override to get behavior similar to an array? I think that providing a method eachwould not be enough, as that would not give me access to the methods []?

Should I inherit the Array class? What should I rewrite there?

+3
source share
3 answers

For an enumerated type of behavior (which looks like what you want), you should include Enumerableget module functionality Enumerable, which means you need to provide a method each. This will give you the many methods you need ( Enumerated data ).

[], :

def [] key
  # return value for key here.
end

def []= key, value
  # store value under key here.
end
+7

. Array, Array, Enumerable.

, , , , super() .

+2

If you have an actual array in which your data is stored, you might want to

require "forwardable"

class CustomArray
  extend Forwardable # For def_delegators
  include Enumerable # Optional

  def_delegators :@actual_array, :[], :[]=, :each

  def initialize(actual_array)
    @actual_array = actual_array
  end
end

Using delegation, you provide only those methods that you know you want, and do not provide all methods by default.

+1
source

All Articles