Dan Garman Dan Garman - 3 months ago 12
Ruby Question

Trim a trailing .0

I have an Excel column containing part numbers. Here is a sample



As you can see, it can be many different datatypes:

Float
,
Int
, and
String
. I am using
roo
gem to read the file. The problem is that
roo
interprets integer cells as
Float
, adding a trailing zero to them (16431 => 16431.0). I want to trim this trailing zero. I cannot use
to_i
because it will trim all the trailing numbers of the cells that require a decimal in them (the first row in the above example) and will cut everything after a string char in the
String
rows (the last row in the above example).

Currently, I have a a method that checks the last two characters of the cell and trims them if they are ".0"

def trim(row)
if row[0].to_s[-2..-1] == ".0"
row[0] = row[0].to_s[0..-3]
end
end


This works, but it feels terrible and hacky. What is the proper way of getting my Excel file contents into a Ruby data structure?

Answer
def trim num
  i, f = num.to_i, num.to_f
  i == f ? i : f
end

trim(2.5) # => 2.5
trim(23) # => 23

or, from string:

def convert x
  Float(x)
  i, f = x.to_i, x.to_f
  i == f ? i : f
rescue ArgumentError
  x
end

convert("fjf") # => "fjf"
convert("2.5") # => 2.5
convert("23") # => 23
convert("2.0") # => 2
convert("1.00") # => 1
convert("1.10") # => 1.1