Skip to content

Commit

Permalink
Added enumerable capabilities. Closes #5.
Browse files Browse the repository at this point in the history
  • Loading branch information
gonzedge committed Jul 21, 2012
1 parent 3776344 commit 3f77b71
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/rambling-trie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
'children_hash_deferer',
'compressor',
'branches',
'enumerable',
'node',
'root',
'version'
Expand Down
20 changes: 20 additions & 0 deletions lib/rambling-trie/enumerable.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module Rambling
module Trie
# Provides enumerable behavior to the Trie data structure.
module Enumerable
include ::Enumerable

alias_method :size, :count

# Calls block once for each of the words contained in the trie. If no block given, an Enumerator is returned.
def each(&block)
enumerator = Enumerator.new do |words|
words << as_word if terminal?
children.each { |key, child| child.each { |word| words << word } }
end

block.nil? ? enumerator : enumerator.each(&block)
end
end
end
end
1 change: 1 addition & 0 deletions lib/rambling-trie/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ class Node
include ChildrenHashDeferer
include Compressor
include Branches
include Enumerable

# Letter or letters corresponding to this node.
# @return [Symbol, nil] the corresponding letter(s) or nil.
Expand Down
37 changes: 37 additions & 0 deletions spec/lib/rambling-trie/enumerable_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
require 'spec_helper'

module Rambling
module Trie
describe Enumerable do
let(:root) { Root.new }
let(:words) { %w(add some words and another word) }

before :each do
words.each { |word| root << word.clone }
end

describe '#each' do
it 'returns an enumerator' do
root.each.should be_a(Enumerator)
end

it 'includes every word contained in the trie' do
root.each { |word| words.should include(word) }
root.count.should == words.count
end
end

describe '#size' do
it 'delegates to #count' do
root.size.should == words.size
end
end

it 'includes the core Enumerable module' do
root.all? { |word| words.include? word }.should be_true
root.any? { |word| word.start_with? 's' }.should be_true
root.to_a.should =~ words
end
end
end
end

0 comments on commit 3f77b71

Please sign in to comment.