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 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.
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"
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 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.
Ruby - replace characters in a string with a symbol
What about gsub(/\S/, '*')
It will find all non-whitespace characters and replace every one of them with *
. \S
is a regex character class matching non-whitespace chars (thanks @jdno).
E.g.
pry> "as12 43-".gsub(/\S/, '*')
=> "**** ***"
So in your case:
def change_word(word)
word.gsub(/\S/, '*')
end
You may also extract the regex outside of the method to optimize it a bit:
CHANGE_WORD_PATTERN = /\S/
def change_word(word)
word.gsub(CHANGE_WORD_PATTERN, '*')
end
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'
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.
Related Topics
API Post with Array Using Http Gem (Or Restclient)
Linking to External File in Ruby on Rails
How to Create Nested Model from Partial Rails 6
Ruby Roo Loaderror: Cannot Load Such File -- Spreadsheet/Note
Knowing When Resque Worker Had Completed Job
Ruby: Unexpected End-Of-Input, Expecting Keyword_End for If Statement
Make Map Marker Direct Link Onclick for Gmaps4Rails
Ruby: How to Dynamically Replace Parameters in Native Pg Gem
Calling Protected Class Method from Instance Method in Ruby
Open Firefox Browser with Ruby Automation Script