Kelvin Matheus
Kelvin Matheus

Reputation: 147

Error with converting a string negative number to an integer when importing in Ruby

My Ruby environment is: Ruby 2.3.1 and Rails 5.0.0.1.

I'm trying to convert a negative string number in an integer, for instance:

When I try to turn this "-2000" in the irb terminal, I got the result expected -2000

But I'm trying to convert this when I import this data from a CSV file.

I'm using the following information:

CSV file

345,­-2000
345,120000

Code file

CSV.foreach("file.csv") do |row|
  p [row[0], row[1]]
  p row[1].to_i
  p row[1].force_encoding('UTF-8').to_i
  p Integer(row[1])
  p Integer(row[1].force_encoding('UTF-8'))
end

I got that:

["345", "­-2000"]
0
0
'Integer': invalid value for Integer(): "\xC2\xAD2000" (ArgumentError)
'Integer': invalid value for Integer(): "\xC2\xAD2000" (ArgumentError)

Using the Integer(), I discovered that the - sign is represented by "\xC2\xAD".

In summary, the to_i method is converting "\xC2\xAD2000" to 0 and the Integer() is trigging an error.

Could someone help with that?

Thanks for your attention.

Upvotes: 2

Views: 307

Answers (1)

user419017
user419017

Reputation:

It looks like you actually have two characters here..

Personally, I would replace this combination of characters with an actual hyphen and then convert to integer:

CSV.foreach("file.csv") do |row|
  p row[1].sub("\xC2\xAD", '-').to_i
end

That, or clean up the source file. Unsure of how you are generating it, but worth looking into.

Upvotes: 1

Related Questions