Created
July 3, 2015 11:28
-
-
Save jpmoral/482a62b22ab2129be34c to your computer and use it in GitHub Desktop.
Hash vs. case
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 StringLookup | |
def self.lookup(string) | |
case string | |
when /^Foo.*$/ then 'group A' | |
when /^F.*$/ then 'group B' | |
when /^Bar.*$/ then 'group C' | |
when /^Baz.*$/ then string.gsub('a', '0') | |
end | |
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
module RegexAndLambdaHash | |
def value_for_key_matching(string) | |
pattern = self.keys.find { |key| key =~ string } | |
value_for(pattern, string) | |
end | |
def value_for(pattern_key, original_key) | |
value = self[pattern_key] | |
if value.respond_to? :call | |
value.call(original_key) | |
else | |
value | |
end | |
end | |
end | |
module StringLookup | |
LOOKUP = { | |
/^Foo.*$/ => 'group A', | |
/^F.*$/ => 'group B', | |
/^Bar.*$/ => 'group C', | |
/^Baz.*$/ => lambda { |x| x.gsub('a','0') }, | |
}.extend RegexAndLambdaHash | |
def self.lookup(string) | |
LOOKUP.value_for_key_matching(string) | |
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
require 'string_lookup' | |
describe StringLookup do | |
subject { StringLookup } | |
it "assigns strings beginning with 'Foo' to 'group A'" do | |
expect(subject.lookup('Foobar')).to eq 'group A' | |
end | |
it "assigns strings beginning with 'F' but not 'Foo' to 'group A'" do | |
expect(subject.lookup('Fbar')).to eq 'group B' | |
end | |
it "assigns strings beginning with 'Foo' to 'group A'" do | |
expect(subject.lookup('Bar')).to eq 'group C' | |
end | |
it "strings beginning with 'Baz' have 'a's changed to '0's" do | |
expect(subject.lookup('Bazaz')).to eq 'B0z0z' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment