How do I add ‘each’ method to Ruby object (or should I extend Array)?

For the general case of implementing array-like methods, yes, you have to implement them yourself. Vava’s answer shows one example of this. In the case you gave, though, what you really want to do is delegate the task of handling each (and maybe some other methods) to the contained array, and that can be automated.

require 'forwardable'

class Results
  include Enumerable
  extend Forwardable
  def_delegators :@result_array, :each, :<<
end

This class will get all of Array’s Enumerable behavior as well as the Array << operator and it will all go through the inner array.


Note, that when you switch your code from Array inheritance to this trick, your << methods would start to return not the object intself, like real Array’s << did — this can cost you declaring another variable everytime you use <<.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)