我正在尝试建立一个由10x10网格组成的战场。
以下是我的代码:
SHIP_HASH = { submarine: 2, destroyer: 3, destroyer: 3, cruiser: 4, aircraftcarrier: 5,}
def print_results
board_layout = Array.new(10, " ").map{|row| Array.new(10, " ")}
row_label = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
column_label = [" ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
end
print print_results
我收到了输出:
[" ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
我想要的是生成如下输出,但我不知道错误是什么。
0 1 2 3 4 5 6 7 8 9
0 . . . . . . . . . .
1 . . . . . . . . . .
2 . . . . . . . . . .
3 . . . . . . . . . .
4 . . . . . . . . . .
5 . . . . . . . . . .
6 . . . . . . . . . .
7 . . . . . . . . . .
8 . . . . . . . . . .
9 . . . . . . . . . .
答案 0 :(得分:2)
所以在ruby中,在方法中评估的最后一件事是返回的内容。所以在你的print results
中,评估的最后一件事就是column_label
的分配,这就是你看到的内容。
以下是代码,请注意在某些情况下使用print
,在其他情况下使用puts
,因为它们执行不同的操作:
SHIP_HASH = { submarine: 2, destroyer: 3, destroyer: 3, cruiser: 4, aircraftcarrier: 5,}
def print_results
board_layout = Array.new(10, ".").map{|row| Array.new(10, ".")}
row_label = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
column_label = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
print "\t"
print row_label.join("\t")
puts
board_layout.each_with_index do |row, i|
print column_label[i]
print "\t"
print row.join("\t")
puts
end
end
print_results
输出:
0 1 2 3 4 5 6 7 8 9
0 . . . . . . . . . .
1 . . . . . . . . . .
2 . . . . . . . . . .
3 . . . . . . . . . .
4 . . . . . . . . . .
5 . . . . . . . . . .
6 . . . . . . . . . .
7 . . . . . . . . . .
8 . . . . . . . . . .
9 . . . . . . . . . .
如果您对此有任何疑问,请与我们联系。
答案 1 :(得分:0)
SHIP_HASH = { submarine: 2, destroyer: 3, destroyer: 3, cruiser: 4, aircraftcarrier: 5,}
def print_results
board_layout = Array.new(10, ".").map{|row| Array.new(10, ".")}
row_label = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
column_label = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
print "\t"
print row_label.join("\t")
puts
board_layout.each_with_index do |row, i|
print column_label[i]
print "\t"
print row.join("\t")
puts
end
end
print_results