1
def replace_characters(name)
    name.downcase.tr('àáäâãèéëẽêìíïîĩòóöôõùúüûũñç ', 'aaaaaeeeeeiiiiiooooouuuuunc-')
end

I want to replace special characters for normal characters but keeping the case.

Examples and their expected outputs:

  • íhávéspécialchárs.jpg // ihavespecialchars.jpg
  • ÍHÁVÉSPÉCIALCHÁRS.JPG // IHAVESPECIALCHARS.JPG
  • /IMG_4834.JPG // /IMG_4834.JPG

Currently, it's replacing fine, but always changing the string to lowercase. Eg: /IMG_4834.JPG -> /img_4834.jpg

developer033
  • 24,267
  • 8
  • 82
  • 108
  • Interesting related information: http://stackoverflow.com/questions/4418196/ruby-unicode-question – user12341234 Apr 11 '16 at 16:30
  • ...specifically http://stackoverflow.com/a/4418681/128421 in the above page. Renaming the files this way is a slippery slope and if it's possible to get characters in the Unicode range then a narrow replacement set will not cover the rest of the missed characters. I'd either refuse to accept files not named according to rules, or accept them as they are and not rename them. – the Tin Man Apr 11 '16 at 22:24

2 Answers2

6

The current implementation of your method is always returning lowercased strings because it's calling #downcase before invoking #tr - removing #downcase should remedy this. Then, without depending on external libraries, you can modify your existing method to cover uppercase characters as well:

def replace_characters(name)
  name.tr('àáäâãèéëẽêìíïîĩòóöôõùúüûũñçÀÁÄÂÃÈÉËẼÊÌÍÏÎĨÒÓÖÔÕÙÚÜÛŨÑÇ ',
          'aaaaaeeeeeiiiiiooooouuuuuncAAAAAEEEEEIIIIIOOOOOUUUUUNC-')
end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Zoran
  • 4,196
  • 2
  • 22
  • 33
3

Use I18n#transliterate

irb(main):004:0> I18n.transliterate("àáäâãèéëẽêìíïîĩòóöôõùúüûũñç")
=> "aaaaaeee?eiiiiiooooouuuuunc"

See How do I replace accented Latin characters in Ruby?

Community
  • 1
  • 1
patkoperwas
  • 1,341
  • 10
  • 14