我是Ruby的新手,我试图通过传递一个高度值和另一个宽度值来创建图表中的两个值。创建之后,我希望能够单独调用图表中的每个点。我知道我需要创建一个哈希和/或数组来存储图表上的每个点,但是我不确定如何迭代每个值。
例如
def graph_area(x, y)
x = 4
y = 2
# Given the above info my graph would have 8 points
# However I'm not sure how to make create an array that returns
# {[x1, y1] => 1, [x1, y2] => 2, [x2, y1] => 3, [x2, y2]...} etc
# output
# 1234
# 5678
end
这种方法是否实用?
答案 0 :(得分:2)
您需要创建数组数组:
def graph_area(x, y)
counter = 0
Array.new(y) { Array.new(x) { counter += 1 }}
end
board = graph_area(4,2)
puts board.map(&:join)
#=>
# 1234
# 5678
您可以使用(0 - 索引)访问特定字段:
board[0][0] #=> 1
答案 1 :(得分:1)
以下是使用each_slice
:
def graph_area(x, y)
(1..x*y).each_slice(x).to_a
end
area = graph_area(4, 2)
# => [[1,2,3,4],[5,6,7,8]]
area[0][0]
# => 1
area[1][2]
# => 7