Class: Array

Inherits:
Object show all
Defined in:
lib/muflax/array.rb,
lib/muflax/align.rb,
lib/muflax/blank.rb,
lib/muflax/deep_dup.rb

Overview

Copyright muflax <[email protected]>, 2013 License: GNU GPL 3 <www.gnu.org/copyleft/gpl.html>

Instance Method Summary collapse

Instance Method Details

#align(str = "\t", alignment: :left, force: false) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/muflax/align.rb', line 40

def align str="\t", alignment: :left, force: false
  just_function = case alignment
                  when :left    ; Proc.new{|e,l,_c| e.ljust(l)   }
                  when :right   ; Proc.new{|e,l,_c| e.rjust(l)   }
                  when :center  ; Proc.new{|e,l,_c| e.center(l)  }
                  when Proc     ; alignment
                  else
                    raise "invalid alignment: #{alignment}"
                  end

  # split all lines
  lines   = []
  columns = 0
  rx      = /[ ]#{str}/ if force

  self.each do |line|
    line    .gsub! rx, str if force
    line    = line.split(str, -1)
    lines   << line
    columns = [columns, line.size].max
  end

  # justify all columns
  lengths = columns.times.map do |column|
    lines.reduce(0){|sum, line| [line[column].str_length, sum].max}
  end

  lines.map! do |line|
    # align columns
    line.map!.with_index do |elem, column|
      # how much the element is internally longer than it appears
      elem_diff = elem.to_s.length - elem.str_length

      just_function.call(elem, lengths[column] + elem_diff, column)
    end

    # join line back together
    line.join(str)
  end

  lines
end

#align!(str = " ", alignment: :left) ⇒ Object



83
84
85
# File 'lib/muflax/align.rb', line 83

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

#deep_dupObject



13
14
15
# File 'lib/muflax/deep_dup.rb', line 13

def deep_dup
  map(&:deep_dup)
end

#fifthObject



22
# File 'lib/muflax/array.rb', line 22

def fifth   ; self[4]  ; end

#fourthObject



21
# File 'lib/muflax/array.rb', line 21

def fourth  ; self[3]  ; end

#rfind(*arg, &block) ⇒ Object



24
25
26
27
# File 'lib/muflax/array.rb', line 24

def rfind *arg, &block
  i = self.rindex(*arg, &block)
  i.nil? ? nil : self[i]
end

#secondObject

silly accessors



19
# File 'lib/muflax/array.rb', line 19

def second  ; self[1]  ; end

#thirdObject



20
# File 'lib/muflax/array.rb', line 20

def third   ; self[2]  ; end

#triangleObject



7
8
9
10
11
12
13
14
15
16
# File 'lib/muflax/array.rb', line 7

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