How to translate Arabic/Persian numbers to english using Ruby?

笑着哭i 提交于 2020-01-21 20:08:31

问题


How can I convert some string that has Arabic/Persian number to English ?

Like if I have :

str1 = "١۲١۲"
str2 = "12١۲"
str3 = "some string that contains persian digits like ١۲"

Is there any function to encode it to english, and if the string contain such number to convert it like end results will be :

str1 = "1212"
str2 = "1212"
str3 = "some string that contains persian digits like 12"

Thanks


回答1:


For these one on one transformations the tr-method is very convenient and fast. It has a mutating counterpart in tr!

#encoding: utf-8

str1 = "١۲١۲"
str2 = "12١۲"
str3 = "some string that contains persian digits like ١۲"

[str1, str2, str3].each{|str| str.tr!('۰١۲۳۴۵۶۷۸۹','0123456789')}

p str1, str2, str3
#"1212"
#"1212"
#"some string that contains persian digits like 12"



回答2:


Since this is not encoding but translation and assuming your problem limits to only those numbers (0-9), you could write a simple 1-to-1 mapping from arabic to english, something like this:

  arabic_to_english = {
  '٩' => 9,
  '٨' => 8,
  '٧' => 7,
  '٦' => 6,
  '٥' => 5,
  '٤' => 4,
  '٣' => 3,
  '٢' => 2,
  '١' => 1,
  '٠' => 0
}

And you just call the hash whenever needed:

   arabic_to_english['٧']

Better if you extract this into a function of course.



来源:https://stackoverflow.com/questions/15041329/how-to-translate-arabic-persian-numbers-to-english-using-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!