Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Created July 11, 2012 07:05
Show Gist options
  • Save tkfm-yamaguchi/3088559 to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/3088559 to your computer and use it in GitHub Desktop.
エクセルのカラム形式文字列(AAなど)を序数に変換
class String
def byte_num(index=0)
bytes.to_a[index]
end
end
def excoltoNum(str) # :nodoc:
return 0 if str.empty?
raise ArgumentError.new("string includes invalid charactor as column name") unless str =~ /^[a-zA-Z]+$/
str.upcase.reverse.each_byte.with_index.inject(0) do |sum, (b, i)|
sum + (26 ** i) * (b - "A".byte_num).succ
end
end
if __FILE__ == $0
puts excoltoNum("A") #=> 1
puts excoltoNum("AA") #=> 27
puts excoltoNum("FX") #=> 180
## SPEC:
#describe "#excoltonum" do
# it "は引数が空文字の時,0を返す" do
# excoltoNum("").should == 0
# end
#
# it "はエクセルカラム形式の文字列を受け取って順数を返す" do
# excoltoNum("A").should == 1
# excoltoNum("B").should == 2
# excoltoNum("Z").should == 26
# excoltoNum("AA").should == 27
# excoltoNum("AB").should == 28
# excoltoNum("FX").should == 180
# excoltoNum("AAA").should == 703
# end
#
# it "は引数が小文字でも正しく順数を返す" do
# excoltoNum("a").should == 1
# excoltoNum("b").should == 2
# excoltoNum("z").should == 26
# excoltoNum("aa").should == 27
# excoltoNum("ab").should == 28
# excoltoNum("fx").should == 180
# excoltoNum("aaa").should == 703
# end
#
# it "は引数がアルファベット以外が含まれている時,例外を投げる" do
# proc { excoltoNum("日本語") }.should raise_error(ArgumentError)
# proc { excoltoNum("A-") }.should raise_error(ArgumentError)
# end
#end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment