Replace words in a string - Ruby
You can try using this way :
sentence ["Robert"] = "Roger"
Then the sentence will become :
sentence = "My name is Roger" # Robert is replaced with Roger
How do I replace words in a string based on words in an Array in Ruby?
I suggest using the form of String#gsub that employs a hash for making substitutions.
strings_to_highlight = ['red', 'blue']
First construct the hash.
h = strings_to_highlight.each_with_object({}) do |s,h|
h[s] = "(#{s})"
ss = "#{s[0].swapcase}#{s[1..-1]}"
h[ss] = "(#{ss})"
end
#=> {"red"=>"(red)", "Red"=>"(Red)", "Blue"=>"(Blue)", "blue"=>"(blue)"}
Next define a default proc for it:
h.default_proc = ->(h,k) { k }
so that if h
does not have a key k
, h[k]
returns k
(e.g., h["cat"] #=> "cat"
).
Ready to go!
string = "Roses are Red, violets are blue"
string.gsub(/[[[:alpha:]]]+/, h)
=> "Roses are (Red), violets are (blue)"
This should be relatively efficient as only one pass through the string is needed and hash lookups are very fast.
replace words in a string and re join them
The problem you're having with your code is that you call input.split(" ")
but you don't save that to anything, and then you check for input == "u" # ...
, and input
is still the entire string, so if you called autocorrect('u')
or autocorrect('you')
you would get "your sister"
back, except for the next line: input.join(" ")
will throw an error.
This error is because, remember input
is still the original string, not an array of each word, and strings don't have a join
method.
To get your code working with the fewest changes possible, you can change it to:
def autocorrect(input)
#replace = [['you','u'], ['your sister']]
#replace.each{|replaced| input.gsub!(replaced[0], replaced[1])}
input.split(" ").map do |word|
if (word == "u" && word.length == 1) || word == "you"
"your sister"
else
word
end
end.join(" ")
end
So, now, you are doing something with each word after you split(" ")
the input, and you are checking each word against "u"
and "you"
, instead of the entire input string. You then map either the replacement word, or the original, and then join them back into a single string to return them.
As an alternative, shorter way, you can use String#gsub
which can take a Hash
as the second parameter to do substitutions:
If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.
def autocorrect(input)
replace = { 'you' => 'your sister',
'u' => 'your sister',
'another word' => 'something else entirely' }
input.gsub(/\b(#{replace.keys.join('|')})\b/, replace)
end
autocorrect("I am u so smitten with utopia you and another word")
# => "I am your sister so smitten with utopia your sister and something else entirely"
the regex in that example comes out looking like:
/\b(you|u|another word)\b/
with \b
being any word boundary.
How to replace the characters in a string
replacements = {
'i' => 'eye', 'e' => 'eei',
'a' => 'aya', 'o' => 'oha'}
word = "Cocoa!55"
word.gsub(Regexp.union(replacements.keys), replacements)
#⇒ "Cohacohaaya!55"
Regexp::union
, String#gsub
with hash.
Replacing a word in a string with user input [RUBY]
The problem is gets also grabs the new line when a user inputs, so you want to strip that off. I made this silly test case in the console
sentence = "hello world"
replace_with = gets # put in hello
replace_with.strip!
sentence.gsub!(replace_with, 'butt')
puts sentence # prints 'butt world'
How to replace text in a ruby string
def convert(mywords,sentence)
regex = /#{mywords.join("|")}/i
sentence.gsub(regex) { |m| m.upcase }
end
convert(%W{ john james jane }, "I like jane but prefer john")
#=> "I like JANE but prefer JOHN"
Ruby - replace words in a string if instances do not match
This is a gsub
that I think will do what you want:
string = 'richard julie richard julie sam letty sam letty'
string.gsub /\b(?!(richard|julie))\w+/, 'richard'
\b
is a word break and ?!(richard|julie)
is a look ahead for not richard
nor julie
. So this is basically a match for a word break and the letters that follow it, where those letters don't match richard
nor julie
How can I replace words in a string with elements in an array in ruby?
You can use
h = {"{{width}}"=>10, "{{length}}"=>20}
s = "The dimension of the square is {{width}} and {{length}}"
puts s.gsub(/\{\{(?:width|length)\}\}/, h)
# => The dimension of the square is 10 and 20
See the Ruby demo. Details:
\{\{(?:width|length)\}\}
- a regex that matches\{\{
- a{{
substring(?:width|length)
- a non-capturing group that matcheswidth
orlength
words\}\}
- a}}
substring
gsub
replaces all occurrences in the string withh
- used as the second argument, allows replacing the found matches that are equal to hash keys with the corresponding hash values.
You may use a bit simpler hash definition without {
and }
and then use a capturing group in the regex to match length
or width
. Then you need
h = {"width"=>10, "length"=>20}
s = "The dimension of the square is {{width}} and {{length}}"
puts s.gsub(/\{\{(width|length)\}\}/) { h[Regexp.last_match[1]] }
See this Ruby demo. So, here, (width|length)
is used instead of (?:width|length)
and only Group 1 is used as the key in h[Regexp.last_match[1]]
inside the block.
Replace all words which don't match a RegExp pattern in Ruby
From your example it appears that you want to replace all words with 'foo'
except words that contain 's'
; namely, 'string'
, 'surrounded'
and 'quotes'
. For that you can simplify /(.+)?s/
to /s/
(e.g., 'beeswax'.match?(/s/) #=> true
).
It's best to use String#gsub on the entire string as it preserves extra spaces between words. If one instead splits the string on spaces, substitutes for each word in the resulting array, and then join
s those elements to form a new string the extra spaces will be removed. For example, if one is old-school and inserts two spaces between sentences, we might have the following.
str = "Hello, I use a string of words, surrounded by quotes. So there."
and want to preserve the two spaces following the period in the resulting string. Moreover, splitting on spaces and then joining the modified words creates an unnecessary array.
Suppose we wish to replace words that do not contain match 's'
or 'S'
with 'foo'
. Words that contain 's'
or 'S'
match the regular expression
r = /s/i
We may then write:
str.gsub(/\w+/) { |s| s.match?(r) ? s : 'foo' }
#=> "foo, foo use foo string foo words, surrounded foo quotes. So foo."
gsub
's argument is a regular expression that matches words.
Consider a second example. Suppose we with to replace all words that neither begin nor end with 's'
or 'S'
with 'foo'
; that is, words that do not match the regular expression
r = /\As|s\z/i
We can do that in the same way:
str.gsub(/\w+/) { |s| s.match?(r) ? s : 'foo' }
#=> "foo, foo foo foo string foo words, surrounded foo quotes. So foo."
Related Topics
Difference Between Integer(Value) and Value.To_I
What Does "+=" (Plus Equals) Mean
Ruby Forgets Local Variables During a While Loop
The Compiler Failed to Generate an Executable File. (Runtimeerror)
Why Can't I Access a Local Variable Inside a Method in Ruby
Detect Key Press (Non-Blocking) W/O Getc/Gets in Ruby
Selenium Scroll Element into (Center Of) View
How to Downgrade from Ruby 1.9.2 to Ruby 1.8.7 to Run Rails 2.0.2
Order Products by Association Count
Putting the Results of Pp (Or Anything Outputted to Console) into a String
Use of Caret Symbol (^) in Ruby
Rvm Does Not Install Ruby 1.9.2 on Snow Leopard: 'Error Running 'Make '
An Algorithm for Converting a Base-10 Number to a Base-N Number