Simple Search and Replace in Ruby
source link: https://fuzzyblog.io/blog/ruby/2020/05/14/simple-search-and-replace-in-ruby.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Simple Search and Replace in Ruby
May 14, 2020
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.
Posted In: #ruby
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK