Skip to content

Instantly share code, notes, and snippets.

@jpmoral
Created July 3, 2015 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpmoral/482a62b22ab2129be34c to your computer and use it in GitHub Desktop.
Save jpmoral/482a62b22ab2129be34c to your computer and use it in GitHub Desktop.
Hash vs. case
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
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
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