Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a spreadsheet "letternamed" column coordinate to an integer?

In spreadsheets I have cells named like "F14", "BE5" or "ALL1". I have the first part, the column coordinate, in a variable and I want to convert it to a 0-based integer column index.

How do I do it, preferably in an elegant way, in Ruby?

I can do it using a brute-force method: I can imagine loopping through all letters, converting them to ASCII and adding to a result, but I feel there should be something more elegant/straightforward.

Edit: Example: To simplify I do only speak about the column coordinate (letters). Therefore in the first case (F14) I have "F" as the input and I expect the result to be 5. In the second case I have "BE" as input and I expect getting 56, for "ALL" I want to get 999.

like image 405
gorn Avatar asked Nov 27 '25 09:11

gorn


1 Answers

Not sure if this is any clearer than the code you already have, but it does have the advantage of handling an arbitrary number of letters:

class String
  def upcase_letters
    self.upcase.split(//)
  end
end

module Enumerable
  def reverse_with_index
    self.map.with_index.to_a.reverse
  end

  def sum
    self.reduce(0, :+)
  end
end

def indexFromColumnName(column_str)
  start = 'A'.ord - 1
  column_str.upcase_letters.map do |c| 
    c.ord - start
  end.reverse_with_index.map do |value, digit_position|
    value * (26 ** digit_position)
  end.sum - 1
end

I've added some methods to String and Enumerable because I thought it made the code more readable, but you could inline these or define them elsewhere if you don't like that sort of thing.

like image 140
Tim Destan Avatar answered Nov 29 '25 22:11

Tim Destan