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 dates between 20080201
and 20080229
inclusive and the other dates present in the list.
I can get the string 20080201..20080229
, so is the best way to convert this to a Range instance? Currently, I am using eval
, but it feels like there should be a better way.
@Purfideas I was kind of looking for a more general answer for converting any string of type int..int
to a Range I guess.
Strings can be converted to arrays using a combination of the split method and some regular expressions. The split method serves to break up the string into distinct parts that can be placed into array element. The regular expression tells split what to use as the break point during the conversion process.
The to_s function in Ruby returns a string containing the place-value representation of int with radix base (between 2 and 36). If no base is provided in the parameter then it assumes the base to be 10 and returns. Syntax: number.to_s(base)
Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.
Range.new(*self.split("..").map(&:to_i))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With