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
Carl Youngblood wrote:
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…).
···
–
Jamis Buck
jgb3@email.byu.edu
ruby -h | ruby -e ‘a=;readlines.join.scan(/-(.)[e|Kk(\S*)|le.l(…)e|#!(\S*)/) {|r| a << r.compact.first };puts “\n>#{a.join(%q/ /)}<\n\n”’