Ruby string encoding problem

Posted by John Prideaux on Stack Overflow See other posts from Stack Overflow or by John Prideaux
Published on 2010-02-19T15:46:12Z Indexed on 2010/04/21 20:43 UTC
Read the original article Hit count: 213

Filed under:

I've looked at the other ruby/encoding related posts but haven't been able to figure out why the following is not working. Likely just because I'm dense, but here's the situation.

Using Ruby 1.9 on windows. I have a set of CSV files that need some data appended to the end of each line. Whenever I run my script, the appended characters are gibberish. The input text appears to be IBM437 encoding, whereas my string I'm appending starts as US-ASCII. Nothing I've tried with respect to forcing encoding on the input strings or the append string seems to change the resultant output. I'm stumped. The current encoding version is simply the last that I tried.

def append_salesperson(txt, salesperson)
  if txt.length > 2
    return txt.chomp.force_encoding('US-ASCII') + %(, "", "", "#{salesperson}")
  end
end

salespeople = Hash[
    "fname", "Record Manager"]

outfile = File.open("ActData.csv", "w:US-ASCII")

salespeople.each do | filename, recordManager |
  infile = File.open("#{filename}.txt")
  infile.each do |line|
    outfile.puts append_salesperson(line, recordManager)
  end
  infile.close
end
outfile.close

© Stack Overflow or respective owner

Related posts about ruby