From: Kristof Bastiaensen Date: 2004-04-23T23:24:13+09:00 Subject: Re: find a best version (of a package) On Fri, 23 Apr 2004 21:17:14 +0900, 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? > > > tnx again for your time :) > > best regards, > saiph My try: r = /ruby-([\d.]+)/ ['ruby-2.2.5', 'ruby-3.2.6', 'ruby-5'].max { |a, b| r.match(a)[1].split(".") <=> r.match(b)[1].split(".") } or shorter: ['ruby-2.2.5', 'ruby-3.2.6', 'ruby-5'].sort_by { |s| /ruby-([\d.]+)/.match(s)[1].split(".") }[-1] (I am not sure which one performs the best). My opinion about programming style is: make things as simple as you can. Don't create extra helper classes etc if you don't need them. Kristof