openmind ☃   October 05, 2007  ☃  Ruby: convert string to range  (, )

You know what they say about necessity.

class RangeException < Exception; end

class Fixnum
  def to_range
    Range.new(self,self)
  end
end

class String
  def to_range
    begin
      md = /(\d+)(\.\.)(\d+)/.match(self)
      raise RangeException, "Invalid range specified" if md.nil?
      md = md.to_a.map{|str| str.to_i}
      raise RangeException, "Invalid range specified" if md[1] > md[3]
      Range.new(md[1],md[3])
    rescue RangeException => e
      puts $!.to_s
    end
  end
end

This could be improved, for example to handle in/exclusive ranges. But for now it works like this:

1007 0 ~/datparser/lib $ irb
>> require 'ToRange'
=> true
>> 10.to_range
=> 10..10
>> "10..10".to_range
=> 10..10
>> "10...10".to_range
Invalid range specified
=> nil
>> "20..10".to_range
Invalid range specified
=> nil

blog comments powered by Disqus