@string = "Sometimes some stupid people say some stupid words"
@string.enclose_in_brackets("some") # => "Sometimes {some} stupid people say {some} stupid words"
该方法应该如何查看封套_in_brackets?请记住,我只想附上整个单词,(我不希望“{Some}次{some}愚蠢......”,“有时”这个词应保持不变
答案 0 :(得分:5)
这只是使用正则表达式的字符串替换。您可以使用单词boundary特殊字符来防止它在您的参数位于另一个单词的中间时与其匹配。并将您的方法放在String
类中,以便您可以直接在类似示例的字符串上调用它。
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.
答案 1 :(得分:1)
使用带有正则表达式/\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"