Display range in ruby

Is there an easy way to map a range to a different kind of range in ruby ​​without repeating across the entire range? Basically what I am trying to achieve is this

## mapping this
range = 1..5
## into this
date_range = (1.year.ago)..(5.years.ago)

      

The best I came up with was the following:

(range.begin.years.ago)..(range.end.years.ago)

      

Is there a way that would allow me to do something like:

range.map {|e| e.years.ago} 

      

+3


source to share


1 answer


Currently (Ruby 2.2.2) there is no better way than simply

(range.begin.years.ago)..(range.end.years.ago)

      

If you look at the Range documentation , you can see that none of the methods implement something like this.

Then there is the included module Enumerable

, which already loses range semantics (determined by the first and last element).

You can neutralize it yourself:



class Range
  def rmap(&b)
    Range.new(yield(self.begin), yield(self.end), exclude_end?)
  end 
end

      

and then do ( years.ago

requires ActiveSupport / Rails):

(1..5).rmap { | a | a.years.ago }

      

Obviously, the block should yield values ​​suitable for creating a range.

+4


source







All Articles