From: Wilson Bilkovich Date: 2006-01-01T13:19:27+09:00 Subject: Re: Tuples/Records/Quicky Objects + Read Only Arrays? On 12/31/05, Christopher Campbell wrote: > Hi, > > Does Ruby have a tuple or quicky object mechanism? I'm new to Ruby and > have become stuck on how to solve the following. > > I'm testing adding items to a container, where each item is a pair of > strings. One is a name and another an alias. As they're added a check > should be performed to see if they're in the container, etc. > > I've been using OCaml for a while, and for this I'd just use a list of > tuples of strings. What's the ruby way of doing this? Iterating over > a container/array is a doddle, that's not the problem. The problem is > really can you have quick pairs without making classes and so on? > > While I'm at it, is there a read only array like container? Don't want > anyone messing with the internal array, they should not know that what's > returned is actually the internal representation or fiddle with it. > Don't care what they do with the elements in the array, only the array > itself. > > class X > def initialize > @elements = Array.new > end > > ... > > def elements > @elements.clone > end > end > > Returning a clone of an array is fine, just wondered if you could > "write-protect" stuff in general. > > The Ruby equivalent of a tuple is pretty much an Array, since the syntax is so lightweight. a = [1, 2] a.first == 1 a.last == 2 Possibly due to champagne, I can't think of a built-in object that behaves the way you want.. but luckily, a quick implementation of it shouldn't be hard: class FunBox def initialize @names = {} @aliases = {} end def <<(pair) @names[pair.first] = pair.last @aliases[pair.last] = pair.first end def alias_for_name(n) @names[n] end def name_for_alias(a) @aliases[a] end end irb(main):060:0> f = FunBox.new => # irb(main):061:0> f<<['joe', 'jim'] => "joe" irb(main):062:0> f.alias_for_name('joe') => "jim" irb(main):063:0> f.name_for_alias('jim') => "joe" irb(main):064:0> Of course, given that you know OCaml, I'm probably telling you exactly nothing you don't know. I'm not aware of a way to freeze instance variables, such that you couldn't still change them with Object#instance_variable_set