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 BackwardIteration | |
def self.included(base) | |
if base.ancestors.include?(ForwardIteration) | |
instance_methods.each do |method| | |
base.class_eval do | |
alias_method "#{method}_reverse", method | |
define_method method do | |
unbound = ForwardIteration.instance_method(method) | |
unbound.bind(self).call | |
end | |
end | |
end | |
end | |
end | |
def map | |
'Backward Iteration' | |
end | |
end | |
module ForwardIteration | |
def map | |
'Forward Iteration' | |
end | |
end | |
class SingleLinkedList | |
include ForwardIteration | |
end | |
class DoubleLinkedList | |
include ForwardIteration | |
include BackwardIteration | |
end | |
puts "" | |
puts SingleLinkedList.new.map | |
#=> ForwardIteration | |
begin | |
puts SingleLinkedList.new.map_reverse | |
rescue | |
puts 'Single has no #map_reverse' | |
end | |
puts DoubleLinkedList.new.map | |
#=> ForwardIteration | |
puts DoubleLinkedList.new.map_reverse | |
#=> BackwardIteration |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment