Created
January 24, 2009 05:44
-
-
Save coreyhaines/51355 to your computer and use it in GitHub Desktop.
String Tokenizer Kata for Code Retreat
This file contains 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
module StringTokenizer | |
VERSION = '0.0.1' | |
def tokenize(context) | |
self.gsub(/\$[^ ]*/) {|match| | |
context[match[1..-1].to_sym] | |
} | |
end | |
end | |
This file contains 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
describe StringTokenizer do | |
def tokenize(string, context = {}) | |
string.extend(StringTokenizer).tokenize(context) | |
end | |
context "with no tokens" do | |
it "returns blank string if given string is blank" do | |
tokenize("").should == "" | |
end | |
it "returns non-blank string unchanged" do | |
tokenize("hello, world").should == "hello, world" | |
end | |
end | |
context "with one token" do | |
it "replaces token with empty string if no value in context" do | |
tokenize("$name is cool").should == " is cool" | |
end | |
it "replaces token with value from context" do | |
tokenize("$name", :name => 'corey').should == 'corey' | |
end | |
it "leaves rest of string unchanged" do | |
tokenize("$name is cool", :name => 'corey').should == 'corey is cool' | |
end | |
end | |
context "with two tokens" do | |
it "replaces each token with the value from the context" do | |
tokenize("$name loves $food", :name => 'corey', :food => 'bacon').should == | |
"corey loves bacon" | |
end | |
it "replaces with blank string the tokens that have no value in context" do | |
tokenize("$name loves $food1 and $food2", :name => 'corey').should == | |
"corey loves and " | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment