Reputation: 10939
@string = "Sometimes some stupid people say some stupid words"
@string.enclose_in_brackets("some") # => "Sometimes {some} stupid people say {some} stupid words"
How should the method enclose_in_brackets look ? Please keep in mind, I want only enclose whole words, (I don't want "{Some}times {some} stupid....", the "sometimes" word should be left unchanged
Upvotes: 1
Views: 867
Reputation: 37141
It's just a string substitution using a regular expression. You can use the word boundary special character to prevent it from matching your parameter when it's in the middle of another word. And put your method inside the String
class so that you can call it directly on a string like in your example.
class String
def enclose_in_brackets(selection)
self.gsub(/(\b#{selection}\b)/i, '{\1}')
end
end
'Sometimes some stupid people say some stupid words'.enclose_in_brackets('some')
# Sometimes {some} stupid people say {some} stupid words.
Upvotes: 5
Reputation: 123927
use word boundary \b with regex /\bsome\b/
irb(main):015:0* x="Sometimes some good people say some good words"
irb(main):029:0* x.gsub(/\b(some)\b/,"{\\1}")
=> "Sometimes {some} good people say {some} good words"
Upvotes: 1