I'm new to Ruby and I'm trying to create what is in essence a graph sheet by passing two values one for height and another for width. After creation I want to be able to call each point in on the graph individually. I know that I need to create a hash and or array to store each point on the graph however I'm not sure how I would iterate each value.
我是Ruby的新手,我试图通过传递一个高度值和另一个宽度值来创建图表表格。创建后,我希望能够单独调用图表中的每个点。我知道我需要创建一个哈希和/或数组来存储图上的每个点,但是我不确定如何迭代每个值。
For example
例如
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
Is this approach even a practical one?
这种方法是否实用?
2 个解决方案
#1
2
You need to create array of arrays:
您需要创建数组数组:
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
You can access specific fields with (0 - indexed):
您可以使用(0 - 索引)访问特定字段:
board[0][0] #=> 1
#2
1
Here is a way of doing it using each_slice
:
以下是使用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
#1
2
You need to create array of arrays:
您需要创建数组数组:
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
You can access specific fields with (0 - indexed):
您可以使用(0 - 索引)访问特定字段:
board[0][0] #=> 1
#2
1
Here is a way of doing it using each_slice
:
以下是使用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