From: Stephen White Date: 2001-05-11T17:02:51+09:00 Subject: [ruby-talk:14984] Re: Array search idiom On Fri, 11 May 2001, James B. Crigler wrote: > Here's a question about a ruby idiom. I have an array that contains > lines with mammal (classification. animal) pairs like the one found > in the code snippet. I need to find the first contiguous list of > primates. Assuming the array is called "a", here's how I solved the > problem. This does what I want, but is there a better way? My take on this is that you're trying to work with insufficiently massaged data. Convert the array into a more useable form first. > a = [ > "insectivora. shrews", "insectivora. moles", "insectivora. hedgehogs", > "dermoptera. flying lemurs", "chiroptera. bats", "primates. tree shrews", > "primates. lemurs", "primates. monkeys", "edentata. sloths", > "edentata. armadillos", "edentata. anteaters", "pholidota. scaly anteaters", > "primates. marmosets", "primates. great apes", "primates. humans", > "lagomorpha. hares", "lagomorpha. rabbits", "lagomorpha. pikas", > "rodentia. mice", "rodentia. rats" > ] Let's convert this to a Hash, using classifications. b = {} a.each {|i| group, animal = i.split /\, / b[group] ||= [] b[group] << animal } That gives you the more friendly form of: b = { "chiroptera"=>["bats"], "rodentia"=>["mice", "rats"], "lagomorpha"=>["hares", "rabbits", "pikas"], "dermoptera"=>["flying lemurs"], "insectivora"=>["shrews", "moles", "hedgehogs"], "primates"=>["tree shrews", "lemurs", "monkeys", "marmosets", "great apes", "humans"], "edentata"=>["sloths", "armadillos", "anteaters"], "pholidota"=>["scaly anteaters"] } So if you want all primates, you can just do: b['primates'] and get: ["tree shrews", "lemurs", "monkeys", "marmosets", "great apes", "humans"] in return. -- spwhite@chariot.net.au