Replace words in a string - Ruby

前端 未结 4 1319
星月不相逢
星月不相逢 2020-12-12 11:50

I have a string in Ruby:

sentence = \"My name is Robert\"

How can I replace any one word in this sentence easily without using complex code

相关标签:
4条回答
  • 2020-12-12 12:01

    You can try using this way :

    sentence ["Robert"] = "Roger"
    

    Then the sentence will become :

    sentence = "My name is Roger" # Robert is replaced with Roger
    
    0 讨论(0)
  • 2020-12-12 12:02
    sentence.sub! 'Robert', 'Joe'
    

    Won't cause an exception if the replaced word isn't in the sentence (the []= variant will).

    How to replace all instances?

    The above replaces only the first instance of "Robert".

    To replace all instances use gsub/gsub! (ie. "global substitution"):

    sentence.gsub! 'Robert', 'Joe'
    

    The above will replace all instances of Robert with Joe.

    0 讨论(0)
  • 2020-12-12 12:18

    First, you don't declare the type in Ruby, so you don't need the first string.

    To replace a word in string, you do: sentence.gsub(/match/, "replacement").

    0 讨论(0)
  • 2020-12-12 12:21

    If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:

    'mislocated cat, vindicating'.gsub('cat', 'dog')
    => "mislodoged dog, vindidoging"
    

    Regular expressions have word boundaries, such as \b which matches start or end of a word. Thus,

    'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
    => "mislocated dog, vindicating"
    

    In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:

    'сіль у кисіль, для весіль'.gsub(/\bсіль\b/, 'цукор')
    => "цукор у кисіль, для весіль"
    
    0 讨论(0)
提交回复
热议问题