Sometimes I need to deal with key / value data.
I dislike using Arrays, because they are not constrained in size (it's too easy to accidentally add more than 2 items, plus you end up needing to validate size later on). Furthermore, indexes of 0
and 1
become magic numbers and do a poor job of conveying meaning ("When I say 0, I really mean head
...").
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?
These Tuples of Ruby Objects get pushed into the TupleSpace with a write method $tuple_space.
Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index. Array indexing starts at 0, as in C or Java.
No, Ruby doesn't have a standard Pair
class.
You could take a look at "Using Tuples in Ruby?".
The solutions involve either using a similar class as yours, the Tuples gem or OpenStruct.
Python has tuple
, but even Java doesn't have one: "A Java collection of value pairs? (tuples?)".
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