Skip to content

Instantly share code, notes, and snippets.

@sent-hil
Created February 16, 2012 18:30
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 sent-hil/1846892 to your computer and use it in GitHub Desktop.
Save sent-hil/1846892 to your computer and use it in GitHub Desktop.
module Iteration
def map
each[0]
end
def to_a
each.split("")
end
end
module ForwardIteration
include Iteration
def each
'Forward'
end
end
module BackwardIteration
include Iteration
def method_missing(method, *args, &blk)
if method.to_s =~ /^(.*)_reverse/
define_each
result = send($1.to_sym)
undef_each
result
end
end
def define_each
class << self
define_method :each do
e = BackwardIteration.instance_method(:each)
e.bind(self).call
end
end
end
def undef_each
class << self
define_method :each do
super()
end
end
end
def each
'Backward'
end
end
class SingleLinkedList
include ForwardIteration
end
class DoubleLinkedList
include BackwardIteration
include ForwardIteration
end
describe 'LinkedList' do
context SingleLinkedList do
subject { described_class.new }
it 'map' do
subject.map.should == 'F'
end
end
context DoubleLinkedList do
subject { described_class.new }
it 'map' do
subject.map.should == 'F'
end
it 'map_reverse' do
subject.map_reverse.should == 'B'
end
it 'returns array from head to tail' do
subject.to_a.should == %w(F o r w a r d)
end
it 'returns array from tail to head' do
subject.to_a_reverse.should == %w(B a c k w a r d)
end
it 'does not override #each method' do
subject.to_a_reverse.should == %w(B a c k w a r d)
subject.to_a.should == %w(F o r w a r d)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment