Stuart Stuart - 27 days ago 11
Ruby Question

Uncover object type after it has been converted to string

I have a rather peculiar issue that I need to workaround, in Ruby.

I receive a list of values, say:

["foo", "0.0", "1", "{}", "[]"]


I want to uncover the actual type of each element, having no power over the fact that it has already been converted to a String type.

My initial attempt was to load each value individually using JSON deserialization, e.g.:

my_list.each |element| do
puts JSON.load(element).class
end


however this has various caveats that mean it doesn't work quite right.

e.g.
JSON.load("0.0").class
will give me
Float
, but
JSON.load("foo").class
will, of course, bomb out. My solution to this was to use a
try/catch
or
rescue
block for when it is an actual string, but it's not reliable as it breaks for custom classes (say I said
s = SomeClass.new, JSON.load("s")
it rescues as a string) and ends up as rather ugly code.

my_list.each |element| do
puts JSON.load(element).class rescue String
end


Alas, the question I have to ask is, does there exist a way to effectively "unconvert" a string and find out the object type of whatever is contained within the string?

Apologies if this issue has been answered, I have searched at great length, and to no avail. Right now, I feel like the answer is "no".

Thanks for any help!

Answer
['foo', "0.0", "1", "{}", "[]"].map { |a| eval a rescue a }
#=> ['foo', 0.0, 1, {}, []]

To get the class:

['foo', "0.0", "1", "{}", "[]"].map { |a| (eval a rescue a).class }
#=> [String, Float, Fixnum, Hash, Array]

I am sure there might be corner cases, but if you have the data you have in your exemplary list it should work..