From: Brian Schroeder Date: 2004-09-23T08:14:34+09:00 Subject: Re: Newbie: Case statement On Wed, 22 Sep 2004 23:33:52 +0100, Graham Foster wrote: > As a newbie I'm confused about the Case construct. All the documentation > I've found states "case operates by comparing the target with EACH of > the expressions after the When keyword" This does NOT appear to happen, > as only the first match is ever actioned, so overlapping WHEN cases are > skipped. def test(x) > case x > when 1..2 > print "In A\n" > when 1..3 > print "In B\n" > when 2..4 > print "In C\n" > end > end > test(2) > only outputs "In A" > I assume this is expected behaviour? (I'm ex-C - and was looking for > fall-through behaviour) > So my underlying question is:- what's the fastest Ruby for checking > which of the 8 possible adjacent cells on a board (2D array) are still > "on the board" > Thx > Graham Hello Graham, what exactly do you want to know? Do you want to test for each cell if it is on the board, def in_board(x, y) (0 <= x) and (x < @width) and (0 <= y) and (y < @height) end or do you want to do something based on the position on the board, in which case the fastest (if not most concise ruby) I can come up with at this hour of the night would be: def position(x, y) return :off_board if (x < 0) or (y < 0) or (@width <= y) or (@height <= y) if (x == 0) if (y == 0) return :top_left elsif (y == @height - 1) return :bottom_left else return :left end elsif (x == @width - 1) if (y == 0) return :top_right elsif (y == @height - 1) return :bottom_right end else return :not_at_border end end But this is not very concise. It is depending on what you want to do? If you have a two dimensional array, you will get in any case nil values for off-board positions, so maybe class Board attr_reader :width, :height def initialize(width, height) @width = width; @height = height @array = Array.new(width) { Array.new(height) { :empty } } end def [](x, y) return nil if (x < 0) or (y < 0) return @array[x][y] end end will be enough for you, because it returns nil for each cell that is off board. regards, Brian Disclaimer: I consider myself also a nuby, so don't take anything for granted I'm proposing. -- Brian Schræ—¦der http://www.brian-schroeder.de/