Newbie: Case statement

James,

I'm aware this is a common approach, but I'm
personally not found of it.

First of all, it confuses readers of the code. What
size board are we really dealing with here? Why do
these loops keep starting at 1 instead of 0?

    Code like:

World = Array.new(rows + 2,Array.new(columns + 2))
(1..rows).each do |row|
  (1..columns).each do |column|

    ...would hardly be confusing to the readers of the code.

Second, it almost always still requires special
cases. For example, in the mentioned Game of Life,
we must be sure organisms are not born into these
border rows, or they'll change the results.

    No special cases. The loops from 1..rows and 1..columns prevent the
unused rows and columns from generating new cells.

Finally, it's wasteful. I realize the memory is
insignificant here, but it might not be in a bigger
application.

    I guess wasteful is in the eye of the beholder. The code is faster
and infinitely more readable at the expense of a few hundred bytes of
memory - that's a trade-off I'll make any day.

My opinion is that it's better to address the real
issue than just hide it away.

    To me, the real issue is the special cases and how to avoid them.

    I'm not going to get into an argument on this, it's just my opinion.
Your opinions may vary :o)

    - Warren Brown

Warren Brown wrote:

World = Array.new(rows + 2,Array.new(columns + 2))

That's buggy. Use this:

world = Array.new(rows + 2) { Array.new(columns + 2) }

Regards,
Florian Gross