Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 936
Chris Mayer Avatar asked Sep 10 '08 05:09

Chris Mayer


People also ask

How do I convert a string to an array in Ruby?

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.

What is TO_S method in Ruby?

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)

How do I convert a string to a number in Ruby?

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.


2 Answers

Range.new(*self.split("..").map(&:to_i)) 
like image 187
ujifgc Avatar answered Oct 19 '22 05:10

ujifgc


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

like image 23
Purfideas Avatar answered Oct 19 '22 03:10

Purfideas