Posted by Alex Levchuk on Sun 20th May 20:22 (modification of post by Aleksandr Levchu view diff)
diff | download | new post
- # A Ruby module that adds edges to indexable collections of Objects
- # Not a DRY Implementation
- #
- # Usage: "ruby ./edges.rb"
- module Edges
- def edges
- @edges || []
- end
- def add_edge(from, to)
- @edges ||= []
- @edges << [from, to]
- class << self[from]
- def neighbors
- @neighbors
- end
- end
- self[from].instance_eval do
- @neighbors ||= []
- @neighbors << to
- end
- end
- def remove_edge(from, to)
- @edges ||= []
- @edges.delete [from, to]
- class << self[from]
- def neighbors
- @neighbors
- end
- end
- self[from].instance_eval do
- @neighbors ||= []
- @neighbors.delete to
- end
- end
- end
- # Testing
- @a = ['source', 'A', 'B', 'C', 'D', 'E', 'target']
- puts
- puts "@edges => #{@a.inspect}"
- puts
- class << @a
- include Edges
- end
- def print_and_eval(expression)
- puts " #{expression.ljust(20)} => #{eval(expression).inspect}"
- end
- @a.add_edge(0, 1)
- @a.add_edge(1, 2)
- @a.add_edge(1, 3)
- @a.add_edge(3, 6)
- puts "After adding edge(s):"
- print_and_eval "@a.edges"
- @a.each_index do |i|
- if @a[i].methods.include? "neighbors"
- print_and_eval "@a[#{i}].neighbors"
- end
- end
- puts
- puts "After removing edge(s):"
- @a.remove_edge(1, 3)
- print_and_eval "@a.edges"
- print_and_eval "@a[1].neighbors"
- puts
Submit a correction or amendment below. (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.