2

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.

3
  • Where did this data come from and/or what is the CSV encoded as? This tutorial might help - justinweiss.com/articles/… Commented Nov 23, 2016 at 16:10
  • @DamienRoche this is a simple file with CSV extension. I did not encode this file. I just use the CSV class to turn each row in a line in an array and. I will see the tutorial. Thanks. Commented Nov 23, 2016 at 16:19
  • force_encoding should only be used in very specific cases; and almost never when opening a file (unless you know there's specific text that doesn't conform to the overall encoding of the file). Instead you should specify the encoding when opening the CSV; see the doc. Commented Nov 23, 2016 at 16:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.