-2

Now what if I'm trying to change just parts of a word? Like "Car" to "cah", or vise versa in "Martha" to "Marther". In the second case, if I just did an if like this:

<if sentance.include? "er"
    user_input.gsub!(/er/, "a")
end > 

It would take all "a"'s in "MArthA", which is not what I want.

Any ideas? For other examples. Replace words in string - ruby

Community
  • 1
  • 1
  • If `str = "Where's Martha, Billy-Bob?"`, you probably want something like `str.gsub(/(?<=\bMarth)a\b/,"er") #=> "Where's Marther, Billy-Bob?"`. `(?<=\bMarth)` is called a *positive lookbehind*. It ensures the character to be replaced (`"a"`) is preceded by a word break (`\b`) followed by the string `"Marth"`, but that is not part of the match. If I knew the sentence contained only one `"Martha"`, I could have used `sub` rather than `gub`. Your mention of "cah" reminded me of the [Crow Mystery](https://www.reddit.com/r/Jokes/comments/1l888r/the_crow_mystery/). – Cary Swoveland Sep 24 '16 at 02:07
  • 1
    You need to define your grammar better, the rules under which these transformations get done. Is it just the last `a`? – tadman Sep 24 '16 at 02:47
  • That crow joke is great. Basically my goal here is to build a text input converter from basic speach to a New England Accent. So using those rules, I'm only really concerned with the end of a word; specifically words that end in As or ERs- as the swap in the vernacular. The a$ might work, but at end of line means what? Does it search the string for words ending in As? Or does it only take the last word in the string- or is that a\z? – Sal Coraccio IV Sep 25 '16 at 13:36

1 Answers1

0

Your example and code indicate exactly opposite results. Assuming you want to replace the last "a" of Martha with "er", This should replace 'a' at the end of the string:

user_input.gsub!(/a$/,'er')

and if the string is "Where's Martha, Billy-Bob?":

user.gsub!(/a\b/,'er')

\b is the word end or beginning matcher

Sid
  • 408
  • 4
  • 7
  • Note that `a$` is end of line, not necessarily end of string (that would be `a\z`). It probably doesn't matter in this case, but in other situations (e.g. data validation) it can be a security hole, so it's good to be aware of. – Henrik N Sep 24 '16 at 10:04