Sha256: 3e240bf890f3f36e8c42ad8a188c528abb1b9f4ec66ce017a54cbd5cfb4a81ae

Contents?: true

Size: 1.45 KB

Versions: 6

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..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

6 entries across 6 versions & 1 rubygems

Version Path
muflax-0.2.3 lib/muflax/array.rb
muflax-0.2.2 lib/muflax/array.rb
muflax-0.2.1 lib/muflax/array.rb
muflax-0.2.0 lib/muflax/array.rb
muflax-0.1.35 lib/muflax/array.rb
muflax-0.1.34 lib/muflax/array.rb