dnwilson
dnwilson

Reputation: 147

Ruby - How to create plot points

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?

Upvotes: 0

Views: 715

Answers (2)

Uri Agassi
Uri Agassi

Reputation: 37409

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

Upvotes: 1

BroiSatse
BroiSatse

Reputation: 44675

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

Upvotes: 2

Related Questions