Skip to content

Instantly share code, notes, and snippets.

@joshnesbitt
Created July 16, 2015 13:24
Show Gist options
  • Save joshnesbitt/d4a0e13562ed60dda73d to your computer and use it in GitHub Desktop.
Save joshnesbitt/d4a0e13562ed60dda73d to your computer and use it in GitHub Desktop.

Revisions

  1. joshnesbitt created this gist Jul 16, 2015.
    60 changes: 60 additions & 0 deletions filter.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    module BannedWordFilter
    class Filter
    class << self

    BANNED_WORDS = %w(
    fuck
    shit
    banned
    )

    BANNED_WORDS_REGEX = /(#{BANNED_WORDS.join('|')})/i

    def run!(text)
    filtered = text.dup.gsub(BANNED_WORDS_REGEX) do |match|
    first_char = match[0]
    middle_chars = match[1...-1]
    last_char = match[-1]

    "#{first_char}#{'*' * middle_chars.size}#{last_char}"
    end

    Result.new(text, filtered)
    end

    end
    end

    class Result

    def initialize(original, clean)
    @original, @clean = original, clean
    end

    def original_text
    @original
    end

    def clean_text
    @clean
    end

    def clean?
    @original == @clean
    end

    end
    end

    def log_result(r)
    puts
    puts "Original: #{r.original_text}"
    puts "Cleaned: #{r.clean_text}"
    puts "Clean?: #{r.clean?}"
    puts
    end

    log_result(BannedWordFilter::Filter.run!("This is a sentence."))
    log_result(BannedWordFilter::Filter.run!("This is a fucking sentence."))
    log_result(BannedWordFilter::Filter.run!("This is a fucking sentence here's a shit."))
    log_result(BannedWordFilter::Filter.run!("This is a fucking sentence here's a shit banned."))