Rick Rick - 1 year ago 101
Ruby Question

Does Ruby have a `Pair` data type?

Sometimes I need to deal with key / value data. I dislike using Arrays, because they are not constrained in size. Furthermore, indexes of

0
and
1
become magic numbers of sort and do a poor job of conveying meaning. Hashes are also not appropriate, as it is possible to accidentally add an extra entry.

I wrote the following class to solve the problem:

class Pair
attr_accessor :head, :tail

def initialize(h, t)
@head, @tail = h, t
end
end


It works great and solves the problem, but I am curious to know: does the Ruby standard library comes with such a class already?

Answer Source

No, Ruby doesn't have any standard Pair class.

You could take a look at this thread.

The solutions involve either using a similar class as yours, this gem or OpenStruct.

Python has tuple, but even Java doesn't have any standard Pair class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download