Skip to content

Instantly share code, notes, and snippets.

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