Okay so I tried using gsub with regex to replace only the entire word, and not part of it. One of the rules is to change "be" to b. But I only want to do it for the individual words.
Original string: I really want to be the best at everything
Modified string: I really want to be the best at everything
Desired string: I really want to b the best at everything
The following code will take in an array of strings and should change "be" to "b".
array = [
"Hey guys, can anyone teach me how to be cool?
I really want to be the best at everything,
you know what I mean? Tweeting is super fun you guys!!!!",
"OMG you guys, you won't believe how sweet my kitten is.
My kitten is like super cuddly and too cute to be believed right?",
"I'm running out of example tweets for you guys, which is weird,
because I'm a writer and this is just writing and I tweet all day.
For real, you guys. For real.",
"GUISEEEEE this is so fun! I'm tweeting for you guys and this tweet is
SOOOO long it's gonna be way more than you would think twitter can handle,
so shorten it up you know what I mean? I just can never tell how long to keep typing!",
"New game. Middle aged tweet followed by #youngPeopleHashTag Example:
Gotta get my colonoscopy and mammogram soon. Prevention is key! #swag"
]
rules = {
"hello" => "hi",
"too" => "2",
"to" => "2",
"two" => "2",
"for" => "4",
"four" => "4",
"be" => "b",
"you" => "u",
"at" => "@",
"and" => "&"
}
def substitutor(strings,subs)
strings.each_with_index do |string,index|
subs.each do |word,substitute|
strings[index].gsub!(/\bword\b/, substitute)
end
end
end
substitutor(array,rules)
If I substituted without using regex, it would give me this: I really want to b the bst at everything
string, but it should bestrings(plural), according to the method definition. - Ed de AlmeidaRegexp.unionis your friend here. Alternate approach: Split into words on spaces and remap individually,joinback into a single string. - tadmanword, it contains the literal string word. - user1934428