Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting numeric string to numeric in Ruby

Tags:

ruby

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
like image 444
brg Avatar asked Nov 21 '13 08:11

brg


2 Answers

You can use BigDecimal#frac to achieve what you want

require 'bigdecimal'

def to_numeric(anything)
  num = BigDecimal.new(anything.to_s)
  if num.frac == 0
    num.to_i
  else
    num.to_f
  end
end

It can handle

#floats
to_numeric(2.3) #=> 2.3

#rationals
to_numeric(0.2E-4) #=> 2.0e-05

#integers
to_numeric(1) #=> 1

#big decimals
to_numeric(BigDecimal.new("2"))

And floats, rationals and integers in form of strings, too

like image 51
Beat Richartz Avatar answered Oct 02 '22 12:10

Beat Richartz


Convert it to Float using String#to_f method. Since ruby using duck typing you may not care if it can be an Integer.

If it looks like a numeric, swims like a numeric and quacks like a numeric, then it probably is a numeric.

But be aware! to_f does not throw any exceptions:

"foobar".to_f # => 0 
like image 40
user2422869 Avatar answered Oct 02 '22 13:10

user2422869