From: Shawn W_ Date: 2009-09-16T20:33:46+09:00 Subject: Re: Making an array wrap, where last index + 1 = first index Aldric Giacomoni wrote: > def class Array2D < Array > def []( index ) > super [] index % self.length > end > end > > How about that? I thought there might be a neat mathematical way to do this but never would have found it by myself. Finding the remainder (% in Ruby) of: array index / array size works nicely. I couldn't plug that code directly into my program and make it work, but I used the % technique. In my case it's a 2D array. I'm using the code by James Gray from the thread http://www.ruby-forum.com/topic/77572#850992, namely: 01 class Array2D 02 03 def initialize(width, height) 04 @data = Array.new(width) { Array.new(height) } 05 end 06 07 def [](x, y) 08 @data[x][y] 09 end 10 11 def []=(x, y, value) 12 @data[x][y] = value 13 end 14 15 end I modified it to incorporate 'wrapping' like so: 01 class Array2D 02 03 attr_accessor :width, :height 04 05 def initialize(width, height) 06 @width = width 07 @height = height 08 @data = Array.new(@width) { Array.new(@height) } 09 end 10 11 def [](x, y) 12 x = x % @width 13 y = y % @height 14 @data[x][y] 15 end 16 17 def []=(x, y, value) 18 x = x % @width 19 y = y % @height 20 @data[x][y] = value 21 end 22 23 end I'm not sure how impressed Rubyists would be with the neatness of this solution but it works. Thx very much. -- Posted via http://www.ruby-forum.com/.