Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby proper data structure for this implementation

I would like to know of any data structure in Ruby that allows us to conveniently store pairs of numbers.

I would like to store pairs of numbers, like coordinates, in a list without regard to order.

So like [(0,0), (0,1), ... (x,y)]

If there are no data structures that will do this, what is the closest I can achieve with something else?

Thanks.

like image 893
user3307307 Avatar asked May 24 '26 19:05

user3307307


2 Answers

Another way is using Struct to define a Pair like that.

Pair = Struct.new(:x, :y) do
  def to_s
    "(#{x}, #{y})"
  end
end

Then, yon can use it as other build-in data structures. [Pair.new(0,0), Pair.new(1,1)].

If you feel the way constructing Pair is too tedious, define a helper method Pair.

def Pair(x, y)
  Pair.new(x, y)
end

At last, [Pair(0,0), Pair(1,1)]

like image 65
Windor C Avatar answered May 26 '26 12:05

Windor C


You can use nested array, like this:

 array = [[0,0], [0,1], ... [x,y]]
like image 20
Maksim Gladkov Avatar answered May 26 '26 10:05

Maksim Gladkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!