# Printing a Tic-Tac-Toe board in Ruby

I have two implementations of a function that prints out a basic board for Tic-Tac-Toe.

Which of these should I include and why?

def display_board(board)
for i in 0...9
print " #{ board[i] }"
if (i+1)%3 != 0
print " |"
elsif i != 9
print " \n#{'-'*11}\n"
end
end
end


def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end


Surely version two.

• It makes no use of control structures such as for or if, it has very low Kolmogorov complexity because of that, and it is good, as it is directly related to difficulty in understanding.

• It lets you see in a single glance what the output will look like.

• Without even understanding the code, I have a visceral attraction to the 2nd version and a repulsion to the first, a reaction that occurs in well under half a second. It's interesting how often these gut reactions to the visual appearance of code turn out to be a correct assessment of readability and other more rigorous complexity metrics. – Jonah Oct 20 '15 at 20:29
• @Jonah I also had that sensation in less than a second, but half a second after I though "What about extensibility?" promptly followed by "Tic-Tac-Tac is only ever 3x3 so extensibility is not a problem". – Caridorc Oct 20 '15 at 20:51
• Yeah, I think it's great mini-lesson in the costs of abstraction, and a reminder to think about the likely changes in your domain, and know when making something brittle but simple is the right choice. – Jonah Oct 20 '15 at 20:59

If I had to pick, I'd take the second version. Not that the first approach is bad, it just needs a refactor. I'd write:

def display_board(board)
puts board.each_slice(3).map { |row| row.join(" | ") }.join("\n" + "-"*11 + "\n")
end