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.
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?
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):
board[0][0] #=> 1
Here is a way of doing it using 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.