From: Minkoo Seo Date: 2006-04-02T18:13:44+09:00 Subject: Gathering ngrams with the highest probability Hi group. I'm writing some scientific applications with Ruby, and found a frequent problem that I want to solve with Ruby. I got tons of instances of NGram whose definition is as follows: NGram = Struct.new :seq, :prob I have a list of instances of NGram like: .... # # # # # # # # # # # # # # # .... What I want to derive from this data is the list of NGram instances each of which is unique with regard to seq. At the same time, the prob of each ngram in the list must be that of the highest prob. For example, from the ngram list I've shown above, I want to derive a list like the folloing: .... # # # # # # # .... What I've written so far is # Sort by prob in descending order ngrams.sort_by { |ngram| # Compare seq # Then, compare prob } result = [] # Collect unique ngrams with the highest prob. ngrams.inject(nil) { |prev, cur| if prev.nil? result << cur prev = cur elsif prev.seq != cur.seq result << cur prev = cur end } return result And it does not seem to be good even to me. Not to mention unwritten sort_by block, I used result = [] statement which might be get rid of. Any idea for better code? Sincerely, Minkoo Seo