Created
October 23, 2012 09:22
-
-
Save rchatley/3937829 to your computer and use it in GitHub Desktop.
Ruby Encoder - Strategy Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Encoder | |
def initialize(algorithm) | |
@algorithm = algorithm | |
end | |
def encode(line) | |
tokens = line.split(" ") | |
results = [] | |
for word in tokens do | |
results << @algorithm.encode_word(word) | |
end | |
results.join(" ") | |
end | |
end | |
class Reverser | |
def encode_word(word) | |
word.reverse | |
end | |
end | |
class Doubler | |
def encode_word(word) | |
word * 2 | |
end | |
end | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require './encoder' | |
describe Reverser do | |
it "reverses each word in the input" do | |
encoder = Encoder.new(Reverser.new) | |
encoder.encode("abcde 123").should == "edcba 321" | |
end | |
end | |
describe Doubler do | |
it "doubles each word in the input" do | |
encoder = Encoder.new(Doubler.new) | |
encoder.encode("abcde 123").should == "abcdeabcde 123123" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment