From: dblack@... Date: 2006-03-25T20:59:58+09:00 Subject: Re: require a certain version of the ruby interpreter Hi -- On Sat, 25 Mar 2006, Robert Klemme wrote: > Ross Bamford wrote: >> On Sat, 2006-03-25 at 11:06 +0900, dblack@wobblini.net wrote: >>> Hi -- >>> >>> On Sat, 25 Mar 2006, Robert Klemme wrote: >>> >>>> Shea Martin wrote: >>>>> This works nicely, but I am sure something like this is already built >>>>> in, but I can't seem to find it. >>>>> >>>>> def require_version( p_ver_str ) >>>>> l_have = VERSION.split('.') >>>>> l_need = p_ver_str.split('.') >>>>> l_need.each_index do |i| >>>>> if l_have[i].to_i < l_need[i].to_i >>>>> raise ScriptError, "Required Ruby #{p_ver_str}, found Ruby >>>>> #{VERSION}" >>>>> end >>>>> end >>>>> end >>>> Hmmm, lettsee whether we can compress that a bit. How about: >>>> >>>> def ensure_version(ver) >>>> raise "Requiring at least #{ver}" unless >>>> RUBY_VERSION.scan(/d+/).map! {|x|x.to_i} >= >>>> ver.scan(/d+/).map! {|x|x.to_i} >>>> end >>>> >>>> Not really a one liner... >>> (What, no inject? :-) I don't think Array has >= though. > > Actually, a version with #inject occurred to me after I sent the other one > out when I thought about reducing redundancy in the code above - you're also > right about Array (strange though as it does implement <=>): Indeed. I don't know why Array doesn't mix in Comparable. > def ev(ver) > raise "Requiring at least #{ver}" unless > [RUBY_VERSION,ver].map! {|v| v.scan(/\d+/).map! {|x|x.to_i}}. > inject {|v1,v2| (v1<=>v2)>=0} > end > >> :) Even I couldn't find an excuse for inject on this one. The best I >> could do was: >> >> def ensure_version(v) >> raise "need #{v}" if VERSION.split('.').zip(v.split('.')).any? {|a,b| a < >> b} >> end > > Nice, too! I like the approach with any?. > >> (given that we don't need to worry about two-digit versions of course). > > You could still to the .to_i when comparing. Here's yet another variation on the theme. (I thought I'd posted this in my previous post but I didn't.) require 'scanf' def ensure_version(need) need.scanf("%d.%d.%d"). zip(RUBY_VERSION.scanf("%d.%d.%d")).any? do |a,b| a > b end and raise "Requires at least #{need}" end I know that two digit numbers aren't on the horizon but it still feels weird to me to do an alphabetical comparison. David -- David A. Black (dblack@wobblini.net) Ruby Power and Light, LLC (http://www.rubypowerandlight.com) "Ruby for Rails" chapters now available from Manning Early Access Program! http://www.manning.com/books/black