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.
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)]
You can use nested array, like this:
array = [[0,0], [0,1], ... [x,y]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With