Testing contents of string for known types

C

Carl Youngblood

Is there a built-in way to test the contents of a string to try and find
a logical type of data that it might contain? For example, say a string
contains "4.56". It would be nice to have

"4.56".inferred_type => Float
"23".inferred_type => Fixnum
"george".inferred_type => String


Thanks,
Carl Youngblood
 
J

Jamis Buck

Carl said:
Is there a built-in way to test the contents of a string to try and
find a logical type of data that it might contain? For example, say a
string contains "4.56". It would be nice to have

"4.56".inferred_type => Float
"23".inferred_type => Fixnum
"george".inferred_type => String

Something like this, perhaps?

class String
def inferred_type
eval(self).class
rescue
String
end
end

p "3.14".inferred_type
p "15".inferred_type
p "george".inferred_type

I'm not sure how robust this is, since it uses eval (if the string
contains the name of a method of String, then the result you get back
will be the class of whatever tha t method returns...).
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top