Reputation: 7702
I have this code:
File.open(name, 'r+') do |f|
new_file = f.read.sub /ApplicationController/, 'AdminController'
f.truncate 0
f.write new_file
f.close
end
and it's supposed to replace ApplicationController with AdminController, then truncate the file, then write the new contents, and then close it.
However, when it truncates the file, and then writes to it, it looks like this:
0000 0000 0000 0000 0ef3
etc...
So truncate is converting the file to hexadecimal. I need it in UTF-8. How can I ensure that the file is UTF-8 before I write to it?
Upvotes: 0
Views: 1312
Reputation: 684
I can't imagine why truncate would be returning hexadecimal characters as it simply returns 0.
To open a file for reading and writing with UTF-8 encoding (also here):
File.open(name, "r+:UTF-8")
Also, you don't need to explicitly close the file when you open it and pass it to a block as Ruby kindly handles that for you when the block exits.
An in depth discussion of Ruby encoding can be found here
Upvotes: 1