本文介绍了如何使在Ruby中可操作的格数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Ruby的一些格子,让这样的输出(不完全,但接近):

I want to make a number grid in Ruby that gives outputs like this (not exactly, but close):

0  1 2 3 4 5 6 7 8 9
   ------------------ 
1 |
2 |
3 |
4 |
5 |
6 |

,其中的空间(坐标点)与随机数填充。我还需要它是可操作的(例如,我可以很容易地找到给它的坐标点的价值,改变它)。我一直在尝试使用这个数组,但还没有找到一个很好的方式得到它在一起。我如何使用Ruby这样做是一种有效的方式?

where the spaces (coordinate points) are filled in with random numbers. I also need it to be manipulatable (e.g. I can easily find the value of a point given it's coordinates and also change it). I've been trying to use arrays for this but haven't yet found a nice way to get it together. How can I do this in an efficient manner using Ruby?

感谢你了!

更新:我有一个这样的数组:

UPDATE: I have an array like this:

 $array = [

        # 0    1    2    3   4    5     6   7    8
        ['O', '-',' -','-', '-', '-', '-', '-', '-'], #0
         ['|', 'x','x','x', 'x', 'x', 'x', 'x', 'x'], #1
         ['|', 'x','x','x', 'x', 'x', 'x', 'x', 'x'], #2
         ['|', 'x','x','x', 'x', 'x', 'x', 'x', 'x'], #3


         ]

我怎么能在友好换眼睛的方式显示它?

How can I display it in a friendly-for-eyes way?

推荐答案

好吧试试这个(见previous答案的编辑,但是这一个是我感觉最好的):

Okay try this (see edits for previous answers, but this one is the best I feel):

grid = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
         [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
         [2, 3, 4, 5, 6, 7, 8, 9, 0, 1],
         [3, 4, 5, 6, 7, 8, 9, 0, 1, 2],
         [4, 5, 6, 7, 8, 9, 0, 1, 2, 3],
         [5, 6, 7, 8, 9, 0, 1, 2, 3, 4],
         [6, 7, 8, 9, 0, 1, 2, 3, 4 ,5] ]

#prints first row and dashed line
r1 = grid[0]
f1 = grid[0][0]
print f1
print "   "
r1.shift
print r1.join(" ")
r1.unshift(f1)
puts ""
puts "   ------------------"

#Prints all other rows
grid.shift
grid.each do |r| 

        f = r[0]
        print f
        print " | "
        r.shift
        print r.join(" ")
        r.unshift(f)
        puts
end

输出:

0   1 2 3 4 5 6 7 8 9
   ------------------
1 | 2 3 4 5 6 7 8 9 0
2 | 3 4 5 6 7 8 9 0 1
3 | 4 5 6 7 8 9 0 1 2
4 | 5 6 7 8 9 0 1 2 3
5 | 6 7 8 9 0 1 2 3 4
6 | 7 8 9 0 1 2 3 4 5

这篇关于如何使在Ruby中可操作的格数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 22:41