Search code examples
rubyspecial-charactersgsub

Replace special characters Ruby


I want to replace all these characters: 'àáäâãèéëẽêìíïîĩòóöôõùúüûũñç' to 'aaaaaeeeeeiiiiiooooouuuuunc'.

Is there a effective way to do this in Ruby? I was thinking about loop each character, but it's not effective.

Thanks.


Solution

  • I would use String#tr which is faster than a Regexp when replacing single characters:

    string = 'hàllò wörld'
    string.tr('àáäâãèéëẽêìíïîĩòóöôõùúüûũñç', 'aaaaaeeeeeiiiiiooooouuuuunc')
    #=> '"hallo world"'