Search code examples
ruby-on-railsrubyregexstrip

Strip not working properly in rails


I have a string

s = "        \r\n Displays the unique ID number assigned to the\r\nAlias Person."

I want to remove this starting space but its not removing even these quotations marks also.

I tried

s = s.strip!
s = s.gsub!('"','')

Solution

  • What you have in your string are non-breaking whitespaces, the difference is somethings non-visible if you don't use any help in your editor:

    p "        \r\n Displays the unique ID number assigned to the\r\nAlias Person."
    p "        \r\n Displays the unique ID number assigned to the\r\nAlias Person."
    

    But if you map each character within the string you can see the difference:

    [32, 32, 32, 32, 32, 32, 32, 32, 13, 10, 32, ...]
    [160, 160, 160, 160, 160, 160, 160, 160, 13, 10, 32, ...]
    

    Those 160 are the ones you can't replace, you must remove them manually, or by rejecting the ones matching 160 and then joining and converting again:

    string = "        \r\n Displays the unique ID number assigned to the\r\nAlias Person."
    p string.chars.reject { |char| char.ord == 160 }.join
    # "\r\n Displays the unique ID number assigned to the\r\nAlias Person."