is there a way to AutoParse a string to another type - e.g. if aDate format then date, else if integ

G

Greg Hauptmann

[Note: parts of this message were removed to make it a legal post.]

Hi,

Is there a way to AutoParse a string to another type - e.g. if a Date format
then date, else if integer than Integer etc

I'm wanting to pass search parameters via a URL, however since everything in
the URL will be a string it would be good to automatically convert a string
to the most likely variable type. In particular differentiating between an
Integer and a Date.

Does this exist somewhere in Ruby already? Or do I have to write myself?

Thanks in advance
 
G

Greg Hauptmann

[Note: parts of this message were removed to make it a legal post.]

thanks - in one line too....so I could do in fact then I guess:

value = Date.parse(string) rescue Integer(string) rescue Float(string)
rescue string
 
G

Greg Hauptmann

[Note: parts of this message were removed to make it a legal post.]

umm...Date parse doesn't seem to be that good, for example see below
?> Date.parse("123", "%d/%m/%Y")
=> Fri, 02 May 2008
 
M

Michael Guterl

umm...Date parse doesn't seem to be that good, for example see below

?> Date.parse("123", "%d/%m/%Y")
=> Fri, 02 May 2008

FWIW, it is assuming you want the 123rd day of the year.

Michael Guterl
 
M

Michael Libby

umm...Date parse doesn't seem to be that good, for example see below

?> Date.parse("123", "%d/%m/%Y")
=> Fri, 02 May 2008
=> Date

As far as I can tell, Date.parse doesn't really want a format string
as the second argument. And Date.parse is working great in your
example, it gave you a date corresponding to the 123rd day of this
year. :)

If you're not sure whether your input string is actually a date, you
might be more interested in Date.strptime:

irb(main):012:0> value = Date.strptime("123", "%d/%m/%y") rescue Integer("123")
=> 123
irb(main):013:0> value.class
=> Fixnum

-Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,732
Latest member
ArronPalin

Latest Threads

Top