views:

3350

answers:

2
+3  Q: 

Tuples in Ruby

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 class in Python, where you can use . notation to find the value for which you are looking. I'm wanting this so that I can create an implementation of D, similar to Dee for Python.

+6  A: 

OpenStruct?

That is _exactly_ what I was looking for. Thanks!
Ryan Riley
np :) to answer you question though: no i do not use tuples in ruby, as openstructs or otherwise. i use classes at the high end and hashes at the low end :)
+5  A: 

Based on the fact that you talk about hashes and . notation I'm going to assume you mean a different kind of tuple than the (1. "a") sort. You're probably looking for the Struct class. eg:

Person = Struct.new(:name, :age)
me = Person.new
me.name = "Guy"
me.age =  30
Logan Capaldo
That's close, but having to name it bugs me. I was looking for something like the (1. "a") sort but with the property get/set notation you describe.
Ryan Riley
@panesofglass, there's no need to name nothing: a = Struct.new(:name, :age).new; a.name = "Guy"
paradoja
Can I set `a = Struct.new(:name, :age)` and later say a.new? I would suppose so. I'll have to check that out. It would be a lot more explicit as to what I want.
Ryan Riley