Пламен обнови решението на 15.12.2011 16:51 (преди около 13 години)
+module GameOfLife
+ class Board
+ include Enumerable
+
+ def initialize(*args)
+ @cells = args.uniq
+ end
+
+ def each(&block)
+ @cells.each &block
+ end
+
+ def [](x, y)
+ @cells.include?([x, y])
+ end
+
+ def next_generation
+ Board.new(*(@cells - dead_cells + born_cells))
+ end
+
+ private
+
+ def neighbours(x, y, arg_hash)
+ all_around = ((x - 1)..(x + 1)).to_a.product(((y - 1)..(y + 1)).to_a) - [[x, y]]
+
+ all_around.select { |neighbour| not (arg_hash[:alive] ^ self[*neighbour]) }
+ end
+
+ def filter_cells(cells, &block)
+ cells.select { |cell| yield neighbours(*cell, alive: true).size }
+ end
+
+ def dead_cells
+ filter_cells(@cells) { |neighbour_count| not (2..3).include?(neighbour_count) }
+ end
+
+ def born_cells
+ empty_cells = map { |cell| neighbours(*cell, alive: false) }.flatten(1).uniq
+
+ filter_cells(empty_cells) { |neighbour_count| neighbour_count == 3 }
+ end
+ end
+end