Skip to content

Instantly share code, notes, and snippets.

@jugyo
Last active December 16, 2015 15:29
Show Gist options
  • Save jugyo/5456435 to your computer and use it in GitHub Desktop.
Save jugyo/5456435 to your computer and use it in GitHub Desktop.
text = File.open('./UTF-16-with-BOM.txt', 'rb') {|f| f.read}
case text[0..1].bytes
when "\xFE\xFF".bytes
encoding = 'UTF-16BE'
when "\xFF\xFE".bytes
encoding = 'UTF-16LE'
else
encoding = 'US-ASCII'
end
puts text.encode('UTF-8', encoding)
@jugyo
Copy link
Author

jugyo commented Apr 25, 2013

We can also do like following:

puts File.open('./UTF-16-with-BOM.txt', 'r:bom|utf-16:utf-8') {|f| f.read}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment