Created
February 16, 2012 18:30
-
-
Save sent-hil/1846892 to your computer and use it in GitHub Desktop.
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 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 |
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
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