Class: Qrio::Matrix

Inherits:
Object
  • Object
show all
Defined in:
lib/qrio/matrix.rb

Direct Known Subclasses

QrMatrix

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bits, width, height) ⇒ Matrix

Returns a new instance of Matrix.



5
6
7
8
9
# File 'lib/qrio/matrix.rb', line 5

def initialize(bits, width, height)
  @bits   = bits
  @width  = width
  @height = height
end

Instance Attribute Details

#heightObject (readonly)

Returns the value of attribute height.



3
4
5
# File 'lib/qrio/matrix.rb', line 3

def height
  @height
end

#widthObject (readonly)

Returns the value of attribute width.



3
4
5
# File 'lib/qrio/matrix.rb', line 3

def width
  @width
end

Instance Method Details

#[](x, y) ⇒ Object



15
16
17
# File 'lib/qrio/matrix.rb', line 15

def [](x, y)
  rows[y][x] rescue nil
end

#[]=(x, y, value) ⇒ Object



19
20
21
22
23
# File 'lib/qrio/matrix.rb', line 19

def []=(x, y, value)
  raise "Matrix index out of bounds" if x >= width || y >= height
  @bits[(width * y) + x] = value
  @rows = @columns = nil
end

#columnsObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/qrio/matrix.rb', line 39

def columns
  @columns ||= begin
    columns = []
    width.times do |index|
      column = []

      rows.each do |row|
        column << row[index]
      end

      columns << column
    end

    columns
  end
end

#extract(x, y, width, height) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/qrio/matrix.rb', line 64

def extract(x, y, width, height)
  new_bits = []
  height.times do |offset|
    new_bits += rows[y + offset].slice(x, width)
  end
  self.class.new(new_bits, width, height)
end

#rotateObject



56
57
58
59
60
61
62
# File 'lib/qrio/matrix.rb', line 56

def rotate
  new_bits = []
  columns.each do |column|
    new_bits += column.reverse
  end
  self.class.new(new_bits, @height, @width)
end

#rowsObject



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/qrio/matrix.rb', line 25

def rows
  @rows ||= begin
    rows = []
    bits = @bits.dup

    while row = bits.slice!(0, @width)
      break if row.nil? || row.empty?
      rows << row
    end

    rows
  end
end

#to_sObject



11
12
13
# File 'lib/qrio/matrix.rb', line 11

def to_s
  "<Matrix width:#{ width }, height: #{ height }>"
end