“漢数字からアラビア数字”を Squeak Smalltalk で

やりたいのは単純で、一〜五十くらいまでで、十一とか三十一とかの表記となる。これを1〜50、11とか31とかに直す。

L'eclat des jours(2010-12-09)
| kjToArabic |
kjToArabic := [:inString |
     | inStream outStream  |
     inStream := inString readStream.
     outStream := String new writeStream.
     [inStream atEnd] whileFalse: [
          | next |
          next := ('十一二三四五六七八九' indexOf: inStream next) - 1.
          (outStream isEmpty and: [next isZero]) ifTrue: [outStream nextPut: $1].
          (next > 0 or: [inStream atEnd]) ifTrue: [outStream nextPutAll: next printString]].
     outStream contents].

kjToArabic value: '一'.       "=> '1' "
kjToArabic value: '十'.       "=> '10' "
kjToArabic value: '十三'.     "=> '13' "
kjToArabic value: '三十'.     "=> '30' "
kjToArabic value: '三十四'.   "=> '34' "


これを直訳っぽく Ruby でも。

class Enumerator
  def end?; peek rescue return true; false end
end 

def kj_to_arabic(str)
  in_strm = str.each_char
  out_str = String.new
  while !in_strm.end?
    nxt = "十一二三四五六七八九".index(in_strm.next)
    out_str << "1" if (out_str.empty? and nxt.zero?)
    out_str << nxt.to_s if nxt > 0 or in_strm.end?
  end
  out_str
end

kj_to_arabic("")       #=> "1"
kj_to_arabic("")       #=> "10"
kj_to_arabic("十三")     #=> "13"
kj_to_arabic("三十")     #=> "30"
kj_to_arabic("三十四")   #=> "34"