Does anyone use tuples in Ruby? If so, how may one implement a tuple? Ruby hashes are nice and work almost as well, but I\'d really like to see something like the Tuple clas
Arrays are cool to use as tuples because of destructuring
a = [[1,2], [2,3], [3,4]]
a.map {|a,b| a+b }
Struct give you convenient .
accessors
Person = Struct.new(:first_name, :last_name)
ppl = Person.new('John', 'Connor')
ppl.first_name
ppl.last_name
You can get the convenience of both worlds with to_ary
Person = Struct.new(:first_name, :last_name) do
def to_ary
[first_name, last_name]
end
end
# =>
[
Person.new('John', 'Connor'),
Person.new('John', 'Conway')
].map { |a, b| a + ' ' + b }
# => ["John Connor", "John Conway"]