Skip to content

Instantly share code, notes, and snippets.

@sattybhens
Created June 6, 2011 19:00
Show Gist options
  • Select an option

  • Save sattybhens/1010837 to your computer and use it in GitHub Desktop.

Select an option

Save sattybhens/1010837 to your computer and use it in GitHub Desktop.
Excel Cell Names
class CellRange
LETTERS = ('A'..'ZZ').to_a
attr_reader :max_col, :min_col, :max_row, :min_row
def initialize(cells)
@cells = cells
@min_row = @min_col = @cells.size
@max_col = @max_row = 0
@sorted_cells = cells.sort_by do|cell|
alpha = column(cell)
numeric = row(cell)
[LETTERS.index(alpha), numeric]
end
end
def valid?
@sorted_cells.size == width * height
end
def width
LETTERS.index(column(@sorted_cells.last)) - LETTERS.index(column(@sorted_cells.first))
end
def height
row(@sorted_cells.last) - row(@sorted_cells.first)
end
def dimensions
"#{row_dimension(@min_col)}#{@min_row}:#{row_dimension(@max_col)}#{@max_row}"
end
def row_dimension(val)
LETTERS[val -1]
end
private
def row(cell_address)
r = cell_address.match(/[0-9]{1,}$/).to_s.to_i
@min_row = r if r < @min_row
@max_row = r if r > @max_row
r
end
def column(cell_address)
alpha = cell_address.match(/^[A-Z]{1,}/).to_s
c = LETTERS.index(alpha) + 1
@min_col = c if c < @min_col
@max_col = c if c > @max_col
alpha
end
end
r = CellRange.new(["A1","A11","A9","AB2","AA1","A10","B1"])
puts r.width
puts r.height
puts r.valid?
puts r.dimensions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment