require 'time'
def to_something(str)
if (num = Integer(str) rescue Float(str) rescue nil)
num
elsif (tm = Time.parse(str)) == Time.now
str
else
tm
end
end
%w{12012 1233.22 12:21:22 10/10/2009 Test}.each do |str|
something = to_something(str)
p [str, something, something.class]
end
Results in
["12012", 12012, Fixnum]
["1233.22", 1233.22, Float]
["12:21:22", Sat Sep 12 12:21:22 -0400 2009, Time]
["10/10/2009", Sat Oct 10 00:00:00 -0400 2009, Time]
["Test", "Test", String]
Update for ruby 1.9.3: the time class in stdlib now throws an exception if it cannot parse the string, therefore:
def to_something(str)
duck = (Integer(str) rescue Float(str) rescue Time.parse(str) rescue nil)
duck.nil? ? str : duck
end
source
share