From: Hugh Sasse Staff Elec Eng Date: 2000-12-08T05:24:03+09:00 Subject: [ruby-talk:6912] Re: Array#rassoc question(s) On Fri, 8 Dec 2000, Dave Thomas wrote: > "Guy N. Hurst" writes: > > > 1) why was Array#rassoc made to look at the second element > > instead of the last element? > > 2) doesn't the current behavior of Array#rassoc conflict with POLS? > > It's a Lisp thing: In list, rassoc returns the first sublist whose cdr > matches. List lists are made of of two element units called conses, > where each cons contains a 'car' and a 'cdr'. So Ruby rassoc follows the > practice and tests the second element. > > Now how _useful_ that is is a separate question ;-) From what I have read about Lisp this week (i.e., I claim no great expertise on this! :-) ) I would say this is quite useful, if you are handling trees in arrays rather than in hashes. If you have a filesystem (a good example of a tree) you might represent the descendents as sublists: ("usr", ("games", ( "fortune", "wumpus"), "local", ("bin", ("ruby")))) and so on. But this is hard to manage with all levels of the recursion. The book on Lisp I've borrowed suggest you would do this: (("usr", "games", "local"), ("games", "fortune", "wumpus"), ("local", "bin"), ("bin", "ruby")) where the head of the list (car) is the parent directory, and the rest of the list pointed to by the cdr holds its child(ren). To meke these into suitable ruby lists (with 2 elements) you would have to group the children: [["usr", ["games", "local"]], ["games", ["fortune", "wumpus"]], ["local", "bin"], ["bin", "ruby"]] which does look a bit more complex, admittedly. Thus each sublist is of the form [parent, child(ren)], so assoc will map from parent to offspring, and rassoc will map from offspring to parent. If you can control where you start the search from, it doesn't matter that /, /usr, and /usr/local usually all have bin subdirectories. A possible Request For Enhancement, perhaps? > > Dave > > Hugh hgs@dmu.ac.uk