I would like to implement a method that converts any given String value into its proper representation. Here are some examples of what I am referring to:
- "TRUE" should become true (TrueClass)
- "1000" should become 1000 (Integer)
- "text" should simply be returned (String)
I believe this has been solved by the code that I have provided, although I am not very pleased with how it looks. I think this could be reworked into something more sophisticated, but my creativity has reached its limit.
def convert(value)
return true if value =~ /^true$/i
return false if value =~ /^false$/i
return value unless value =~ /^[0-9]*$/
begin
Integer(value)
rescue ArgumentError
nil
end
end
My question is essentially: Is there a way to provide the same functionality but with fewer return statements and overall less code?