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

后端 未结 8 2131
一生所求
一生所求 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-30 00:10

    assuming you want the range to iterate properly through months etc, try

    require 'date'
    
    ends = '20080201..20080229'.split('..').map{|d| Date.parse(d)}
    (ends[0]..ends[1]).each do |d|
      p d.day
    end
    
    0 讨论(0)
  • 2020-12-30 00:12

    If we do it like

    v= "20140101..20150101"
    raise "Error: invalid format: #{v}" if /\d{8}\.\.\d{8}/ !~ v
    r= eval(v)
    

    and the attacker has a way of bypassing the raise check (simply by means of manipulating the runtime to disable exceptions) then we can get a dangerous eval which will potentially destroy the universe.

    So for the sake of reducing attack vectors, we check the format, and then do the parsing manually, then check the results

    v= "20140101..20150101"
    raise "Error: invalid format: #{v}" if /\d{8}\.\.\d{8}/ !~ v
    r= Range.new(*v.split(/\.\./).map(&:to_i))
    raise "Error: invalid range: #{v}" if r.first> r.last
    
    0 讨论(0)
提交回复
热议问题