开发者

How to overwrite the dots in a ruby range?

开发者 https://www.devze.com 2022-12-18 06:54 出处:网络
Is there any possibility to overwrite the dots in a r开发者_高级运维uby range?. My aim is, to manipulate the given objects before the range is created.

Is there any possibility to overwrite the dots in a r开发者_高级运维uby range?. My aim is, to manipulate the given objects before the range is created.

I thought of something like this

require 'rubygems'
require 'active_support'

#actual i have to call explicitly .to_date
Date.today.to_date..1.month.since.to_date

#this should give me a range with Date objects
Date.today..1.month.since

I have already tried to overwrite the initialize method of the class Range. But this hasn't worked as expected.


I just had a look at the MRI 1.8.7 source and found a bit of a surprise. Long story short, you can override Range.initialize, but Ruby doesn't call Range.initialize when initializing a range created with the .. or ... operator. I can't see any obvious reason it was done that way. Speed, if I had to guess.


You can override the behaviour of Range.new by redefining initialize but this will not affect the range literal:

class Range
    alias_method :orig_init, :initialize
    def initialize(b, e, *args)
        orig_init(b * 10, e * 10, *args)
    end
end

Range.new(1, 2) #=> 10..20

1..2 #=> 1..2


I know you said you want to overwrite the .. is that a strict requirement or you just want to?

The following gives you an array of date objects in the range. It might not handle all of the cases and requires tweaking. I don't know why you'd be opposed to pursuing something like this though.

require 'active_support'

def daterange(datestart,dateend)
datearray = []
myrange = (datestart.to_date - dateend.to_date).to_i.abs

myrange.times do |x|
  datearray << datestart + x.day
end

datearray

end


puts daterange(Date.today,1.month.since)
0

精彩评论

暂无评论...
验证码 换一张
取 消