pastebin - collaborative debugging

pastebin is a collaborative debugging tool allowing you to share and modify code snippets while chatting on IRC, IM or a message board.

This site is developed to XHTML and CSS2 W3C standards. If you see this paragraph, your browser does not support those standards and you need to upgrade. Visit WaSP for a variety of options.

Ruby paste-bin - collaborative debugging tool View Help


Posted by Alex Levchuk on Sun 20th May 20:22 (modification of post by Aleksandr Levchu view diff)
diff | download | new post

  1. # A Ruby module that adds edges to indexable collections of Objects
  2. # Not a DRY Implementation
  3. #
  4. # Usage: "ruby ./edges.rb"
  5.  
  6. module Edges
  7.   def edges
  8.     @edges || []
  9.   end
  10.  
  11.   def add_edge(from, to)
  12.     @edges ||= []
  13.     @edges << [from, to]
  14.  
  15.     class << self[from]
  16.       def neighbors
  17.         @neighbors
  18.       end
  19.     end
  20.  
  21.     self[from].instance_eval do
  22.       @neighbors ||= []
  23.       @neighbors << to
  24.     end
  25.   end
  26.  
  27.   def remove_edge(from, to)
  28.     @edges ||= []
  29.     @edges.delete [from, to]
  30.  
  31.     class << self[from]
  32.       def neighbors
  33.         @neighbors
  34.       end
  35.     end
  36.  
  37.     self[from].instance_eval do
  38.       @neighbors ||= []
  39.       @neighbors.delete to
  40.     end
  41.   end
  42. end
  43.  
  44.  
  45. # Testing
  46.  
  47. @a = ['source', 'A', 'B', 'C', 'D', 'E', 'target']
  48. puts
  49. puts "@edges => #{@a.inspect}"
  50. puts
  51.  
  52.  
  53. class << @a
  54.   include Edges
  55. end
  56.  
  57.  
  58. def print_and_eval(expression)
  59.   puts "  #{expression.ljust(20)} => #{eval(expression).inspect}"
  60. end
  61.  
  62.  
  63. @a.add_edge(0, 1)
  64. @a.add_edge(1, 2)
  65. @a.add_edge(1, 3)
  66. @a.add_edge(3, 6)
  67.  
  68. puts "After adding edge(s):"
  69. print_and_eval "@a.edges"
  70. @a.each_index do |i|
  71.   if @a[i].methods.include? "neighbors"
  72.     print_and_eval "@a[#{i}].neighbors"
  73.   end
  74. end
  75. puts
  76.  
  77.  
  78. puts "After removing edge(s):"
  79.  
  80. @a.remove_edge(1, 3)
  81. print_and_eval "@a.edges"
  82. print_and_eval "@a[1].neighbors"
  83. 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.

Use syntax highlighting

To highlight particular lines, prefix each line with @@
:
:
Remember my settings