Make something enumerable
It can sometimes be useful for an object to be Enumerable, so we can call
methods like map
, max
, etc. There’s basically two steps:
include Enumerable
- Define an
each
method. Enumerable methods rely oneach
.
This example comes from an exercise I did on Exercism.
class CharSet include Enumerable def initialize(text) @text = text @members = text.split("\n").map(&:chars) end def each(&block) if block_given? @members.each(&block) else to_enum(:each) end end def max_length map(&:length).max || 0 end def transpose max_length.times.each_with_object([]) do |n, a| a << Row.new(map { |member| member[n] }) end end end
See also