Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Ruby have a `Pair` data type?

Tags:

ruby

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?

like image 597
Rick Avatar asked Feb 07 '17 15:02

Rick


People also ask

Does Ruby have tuples?

These Tuples of Ruby Objects get pushed into the TupleSpace with a write method $tuple_space.

What is the name for a Ruby data structure that uses an integer index?

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.


1 Answers

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?)".

like image 102
Eric Duminil Avatar answered Oct 09 '22 23:10

Eric Duminil