Sha256: 894fb2af159cf50cc26b123cada06d546a1b9c7d1d07f067577b2c6b8f162467

Contents?: true

Size: 1.45 KB

Versions: 3

Compression:

Stored size: 1.45 KB

Contents

#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
# Copyright muflax <mail@muflax.com>, 2013
# License: GNU GPL 3 <http://www.gnu.org/copyleft/gpl.html>

class Array
  def align str=" ", alignment: :left
    lines = []
    columns = 0

    # split all lines
    self.each do |line|
      line = line.split(str, -1)
      lines << line
      columns = [columns, line.size - 1].max
    end

    just_function = case alignment
                    when :left   ; :ljust
                    when :right  ; :rjust
                    when :center ; :center
                    else
                      raise "invalid alignment: #{alignment}"
                    end

    # justify all columns
    0.upto(columns).each do |column|
      length = lines.map{|line| line[column]}.length_of_longest

      lines.each do |line|
        elem = line[column]
        unless elem.nil?
          # how much the element is internally longer than it appears
          elem_diff = elem.to_s.length - elem.str_length

          line[column] = elem.send(just_function, length + elem_diff)
        end
      end
    end

    # join lines back together
    lines.map{|line| line.join(str)}
  end

  def align! str=" ", alignment: :left
    self.replace(self.align(str, alignment: alignment))
  end

  def triangle
    return to_enum(:triangle) unless block_given?

    self.each.with_index do |a, ai|
      self.each.with_index do |b, bi|
        next if bi < ai
        yield [a, b]
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
muflax-0.2.6 lib/muflax/array.rb
muflax-0.2.5 lib/muflax/array.rb
muflax-0.2.4 lib/muflax/array.rb