# Simple Search and Replace in Ruby

DevFeed: [Simple Search and Replace in Ruby](<https://devfeed.tech/articles/simple-search-and-replace-in-ruby-28313.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/ruby/2020/05/14/simple-search-and-replace-in-ruby.html>)

Author: Fuzzygroup

Published: 2020-05-14T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Ruby](<https://devfeed.tech/topics/ruby.md>), [Regular expression](<https://devfeed.tech/topics/regular-expression.md>), [Library](<https://devfeed.tech/topics/library.md>)

Tags: [expression](<https://devfeed.tech/tags/expression.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [search](<https://devfeed.tech/tags/search.md>), [stack-overflow](<https://devfeed.tech/tags/stack-overflow.md>)

## AI overview

A Ruby search-and-replace technique for converting regular-expression matches to strings: use sub or gsub with a literal string instead of a pattern when appropriate.

## Source excerpt

The other day I needed to take some regular expressions and convert them to strings. And while executing a .to_s on the regular expression itself worked correctly it brought through the regular expression characters so there were things like: covid[ -]19 where what I was looking for was just the "covid19" bit (I was generating hashtags from the matched regular expressions for the new CovidNearMe News Aggregator). I started digging into the Ruby string library and didn't find what I was looking for - a str_replace like command. I also experimented a bit with tr but that proved to be misleading at best. Not surprisingly, Stack Overflow came to the rescue and the answer was blindingly simple: Use sub Use gsub but don't specify a pattern; just specify a string. If you don't have: .gsub(/foo/,'bar') but instead .gsub('foo','bar') With this approach, you can then either use sub or gsub depending on how you need the search and replace executed. This is a truly ruby-esque approach and one I should have anticipated.