What is the best way to convert a Ruby string range to a Range object

Range.new(*self.split("..").map(&:to_i))

Inject with no args works well for two element arrays:

rng='20080201..20080229'.split('..').inject { |s,e| s.to_i..e.to_i }

Of course, this can be made generic

class Range
  def self.from_ary(a)
    a.inject{|s,e| s..e }
  end
end

rng = Range.from_ary('20080201..20080229'.split('..').map{|s| s.to_i})
rng.class  # => Range

But then just do

ends = '20080201..20080229'.split('..').map{|d| Integer(d)}
ends[0]..ends[1]

anyway I don't recommend eval, for security reasons

Tags:

Ruby