Alex's Slip-box

These are my org-mode notes in sort of Zettelkasten style

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:

  1. include Enumerable
  2. Define an each method. Enumerable methods rely on each.

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

Search Results