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

后端 未结 8 2189
一生所求
一生所求 2020-12-29 23:38

I have some Ruby code which takes dates on the command line in the format:

-d 20080101,20080201..20080229,20080301

I want to run for all da

8条回答
  •  甜味超标
    2020-12-29 23:55

    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
    

提交回复
热议问题