Skip to content

Instantly share code, notes, and snippets.

@carlism
Created January 18, 2011 02:10
Show Gist options
  • Save carlism/783877 to your computer and use it in GitHub Desktop.
Save carlism/783877 to your computer and use it in GitHub Desktop.
small parsing exercise
def parse(name)
results = []
tokens = name.split(/(\[[^\]]*\])/).reject{|s| s.empty? }
permutations = 2**tokens.count{|s| s.start_with?("[") }
permutations.times do |permutation|
result = ""
opt_count = 1
tokens.each do |word|
if word.start_with?("[")
if (opt_count & permutation) > 0
result<<word[1..-2]
end
opt_count+=1
else
result<<word
end
end
results << result
end
results
end
describe "parse" do
it 'should list all permutations, text in brackets is optional' do
strings = parse('foo[bar]')
strings.should include('foo')
strings.should include('foobar')
strings.should_not include('bar')
strings.size.should == 2
end
it 'should list all permutations, text in brackets is optional' do
strings = parse('[foo]bar[baz]')
strings.should include('foobar')
strings.should include('bar')
strings.should include('barbaz')
strings.should include('foobarbaz')
strings.should_not include('foo')
strings.should_not include('baz')
strings.size.should == 4
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment