Off the top of my head, some simple ways to make this shorter:<p><pre><code> * Use 0...s*s instead of 0..s*s-1
* Use 0..s*s instead of 0...s*s (overrunning g doesn't matter much)
* Use count{|x|x} instead of compact.count
* Get rid of ||nil (because count{|x|x} ignores all falsy values)
* Get rid of the brackets around g[i]&&n==2
* Use [g[i-s-1,3],g[i-1],g[i+1],g[i+s-1,3]].flatten instead of [[g[i-s-1],g[i-s],g[i-s+1],g[i-1],g[i+1],g[i+s-1],g[i+s],g[i+s+1]]
* Use -1..s*s instead of 0..s*s and substitute i+1 for i (i.e. g[i+1] instead of g[i], but [g[i-s,3],g[i],g[i+2],g[i+s,3]] instead of [g[i-s-1,3],g[i-1],g[i+1],g[i+s-1,3]])</code></pre>