On Tue, 28 Nov 2000, Dave Thomas wrote: > David Alan Black <dblack / candle.superlink.net> writes: > > > What about a to_h method for arrays? I mention this mainly for the > > sake of symmetry with other to_* methods. Then again, such a method > > may violate some principle of design: it does seem slightly wrong for > > Array to "know" how to generate a hash (whereas not strange for Hash > > to know how to create itself from an array). > > That was my thinking (if you can call it that ;-) It seems reasonable > for a more complex class to know about a more primitive one, but not > the other way around. Although.... what about the cases where two types have to_* methods for each other? (Array#to_s, String#to_a, for example) Are all such types considered lateral to each other, on the scale of complexity? Or maybe the difference is that a-to-s/s-to-a don't introduce new data, whereas hashing an array against a bunch of 1's adds a bunch of 1's. There's another way to look at it, though -- somewhat Devil's advocate, but anyway. Arrays and hashes are both indexed collections of elements, with the one singularity that the indices of arrays are integers. From that perspective, a case could be made that changing an array to a hash really wouldn't involve anything that wasn't part of the array already. But this would depend on doing it, not as we've been discussing so far, but like this: class Array def to_h h = {} each_index { |i| h[i] = at i } h end end %w{ list of words }.to_h # => {0=>"list", 1=>"of", 2=>"words"} One could then invert the hash to get at least one version of the original effect -- namely, the original array elements as hash keys and all the values true. (Even zero!) In short: just as a string knows enough to break itself down into an array, an array could perhaps reasonably know enough to present itself as a hash, if all that's involved is lining up the indices and the elements and letting them be called something else (i.e., without interpolating anything new). Well, that's about the best case I can make for this. I'm not as unconvinced by it as I thought I would be :-) Comments encouraged. David -- David Alan Black home: dblack / candle.superlink.net work: blackdav / shu.edu Web: http://pirate.shu.edu/~blackdav