I want a method like to_numeric(str) which convert numeric string 'str' into its numeric form else return nil. By numeric form if string is in integer method should return integer and it string is in float it should return float.
I have tried with following code. It works fine but need better solution if possible.
def to_numeric(str)
Integer(str)
rescue
Float(str) if Float(str) rescue nil
end
One important thing I forgot to mention is "I don't know the type of my input".
My use case:
arr = [1, 1.5, 2, 2.5, 4]
some_input = get_input_from_some_source
if arr.include?(to_numeric(some_input))
# do something
end
to_imethod for string class ruby-doc.org/core-1.9.3/String.html#method-i-to_ito_igives integer or float, particularly, an integer.[4].include? 4.0 #=> truemyInput.to_fwould do the trick, but if it's your precise use case, then you may need to change it. Comparisons betweenfloats/doubles/..is not always what you'd expect. The number1.5might not be possible to store exactly-like-it-is in a "numeric type". It might be1.5000000001. If after parsing the input you get1.49999999, you wouldn't find it in the array by simpleinclude?.