How can I remove the string “\n” from within a Ruby string?

前端 未结 6 1055
迷失自我
迷失自我 2020-12-12 13:21

I have this string:

\"some text\\nandsomemore\"

I need to remove the \"\\n\" from it. I\'ve tried

\"some text\\nandsomemore         


        
相关标签:
6条回答
  • 2020-12-12 13:42

    Look here:

    • How to replace multiple newlines in a row with one newline using Ruby
    0 讨论(0)
  • 2020-12-12 13:48

    When you want to remove a string, rather than replace it you can use String#delete (or its mutator equivalent String#delete!), e.g.:

    x = "foo\nfoo"
    x.delete!("\n")
    

    x now equals "foofoo"

    In this specific case String#delete is more readable than gsub since you are not actually replacing the string with anything.

    0 讨论(0)
  • 2020-12-12 13:52

    If you want or don't mind having all the leading and trailing whitespace from your string removed you can use the strip method.

    "    hello    ".strip   #=> "hello"   
    "\tgoodbye\r\n".strip   #=> "goodbye"
    

    as mentioned here.

    edit The original title for this question was different. My answer is for the original question.

    0 讨论(0)
  • You don't need a regex for this. Use tr:

    "some text\nandsomemore".tr("\n","")
    
    0 讨论(0)
  • 2020-12-12 13:56

    You need to use "\n" not '\n' in your gsub. The different quote marks behave differently.

    Double quotes " allow character expansion and expression interpolation ie. they let you use escaped control chars like \n to represent their true value, in this case, newline, and allow the use of #{expression} so you can weave variables and, well, pretty much any ruby expression you like into the text.

    While on the other hand, single quotes ' treat the string literally, so there's no expansion, replacement, interpolation or what have you.

    In this particular case, it's better to use either the .delete or .tr String method to delete the newlines.

    See here for more info

    0 讨论(0)
  • 2020-12-12 14:00

    use chomp or strip functions from Ruby:

    "abcd\n".chomp => "abcd"
    "abcd\n".strip => "abcd"
    
    0 讨论(0)
提交回复
热议问题