From: Mark Hubbart Date: 2004-04-24T02:37:57+09:00 Subject: Re: find a best version (of a package) On Apr 23, 2004, at 5:17 AM, saiph wrote: > > hi list, > > > i'm following the "learning ruby" path, i've found this list very > usefull the > last time (tnx), so i thought to send this simple example to better > understand what'd to be a good programming style. > > > > alea> expand -t 2 best_vv > ----------------------------------------------- > class String > def newer?(s) > b = self.dup > > b.sub!(/(\w+-)/, '') > t = $+ > s.sub!(/(\w+-)/, '') > > return -1 if t != $+ # not the same package > > while (b.sub!(/(\d+\.|\d+)/, '')) do > t = $+.chomp('.') > s.sub!(/(\d+\.|\d+)/, '') > > return 1 if $+ == nil > return 1 if t.to_i > $+.chomp('.').to_i > end > > return 0 > end > end > > class Array > def best_version? > s = 0 > > for i in 1..self.length() - 1 do > t = self[i].newer? self[s] > if t == 1 > s = i > elsif t == -1 > return nil > end > end > > return s > end > end > > vv = ['ruby-2.2.5', 'ruby-3.2.6', 'ruby-5'] > i = vv.best_version? > puts vv[i] > ----------------------------------------------- > > how would you write or change this? first, I would suggest more comments in the code :) at least something above the method telling what it does. That makes it so others can see at a glance what it is for, and rdoc can document it properly. query methods (foo?()) generally return true/false. Also, I suspect that comparing different packages should raise an error, not return -1. Otherwise, I think maybe it could be condensed down a bit... class String # compares package version strings def newer?(other) this, that = split(/-/), other.split(/-/) # check that package names match if this[0] != that[0] raise ArgumentError, "package names do not match" end # compare each section this[1].split(".").zip( that[1].split(".") ) do |a,b| a, b = a.to_i, b.to_i return a > b if a != b end # neither one was larger: return false end end class Array # returns the highest version string in an array def best_version inject{|a,b| a.newer?(b) ? b : a } end end cheers, --Mark