Guest User

Untitled

a guest
Sep 19th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. # encoding: UTF-8
  3.  
  4. # Notice I set UTF-8 as the default above. As far as I'm concerned there
  5. # are two choices of encoding: UTF-8, and legacy crap. If I need to deal
  6. # with anything else I'll handle it explicitly, as in this example.
  7.  
  8. # Open an ISO-8859-1 file.
  9. infile = File.open("iso88591.txt", "r:iso-8859-1")
  10.  
  11. # Read a line from the file. Even though we've specified a default encoding
  12. # in this script, the line we read in stays in the encoding specified when
  13. # the file was opened.
  14. line = infile.gets
  15. puts "Line of text in original encoding:"
  16. puts line
  17. # Line shows up as garbage in my Linux terminal, which is UTF-8.
  18.  
  19. # Now convert it to UTF-8 and redisplay it
  20. uline = line.encode("UTF-8")
  21. puts "Line of text in UTF-8:"
  22. puts uline
  23. # This time it shows up correctly.
  24.  
  25. # Now we'll write out to a new file.
  26. outfile = File.open("utf8.txt", "w:UTF-8")
  27. outfile.puts line
  28. # Ruby automatically converts the ISO-8859-1 string
  29. # to UTF-8 before writing to the file.
  30.  
  31. outfile.close
  32. infile.close
Add Comment
Please, Sign In to add comment