Viewing Posts from April, 2008

Filtering out Swear words in Ruby

     I was looking around for a quick couple of lines of code that would search out any string for a swear word and replace it with a cleaner word. I had a little trouble finding an easy example, so here's one for you. I use a modified version of this script for a lot of my applications:

 $ nano filter_swear_words.rb

#!/usr/bin/ruby
@string = "What the funk"

@bad_words = Hash.new
@bad_words[:funk] = "funny" #the [:funk] is the bad word, and the "funny" is the replacement@bad_words[:shoot] = "shucks" # add more in this fashion 

@seperated_words =  @string.split(" ") # seperate content by spaces

print "Original String: #{@string}\n"

@cleaned_string = ""

for word in @seperated_words
 @bad_words.each do |bad_word, replacement|
  if word == bad_word.to_s # if the word we're looking at is bad

   word = replacement # replcae the word 

   else # the word is we're looking at is okay
   end
 end

 @cleaned_string << word + " "
end

print "Cleaned String: #{@cleaned_string}\n"

So when we run the script, here's what we get:

$ ruby filter_swear_words.rb
Original String: What the funk
Cleaned String: What the funny

Comment_add  (0) Comments


Tags:


Powered_by_amethyst
Archive
Search
Tags
          Databases (1)
          General (2)
          Hosting (1)
          Hulihan Applications (3)
          Programming (1)
          Ruby (2)
          Ruby on Rails (6)
          Servers (1)
          Software (2)
view rss feed
This site is best displayed in FireFox 1.5+, IE 7+, and Opera 9+