Call iconv from Ruby 1.8.7 through system to conve

2019-08-07 12:52发布

Here's what I got:

path_js = 'path/to/a/js/file.js'
path_new_js = 'path/where/the/converted/file/should/go.js'
puts('iconv -f utf-16le -t utf-8 ' + path_js + ' > ' + path_new_js)
system('iconv -f utf-16le -t utf-8 ' + path_js + ' > ' + path_new_js)

The output of the puts statement is:

iconv -f utf-16le -t utf-8 path/to/1-1-2_E1_MC105.js > compiled/path/to/1-1-2_E1_MC105.js

If I copy-paste that exact same line in my terminal the conversion takes place successfully but when it runs inside my ruby script, the new file is created with the same encoding as the original file (utf-16 in this case). Any ideas on what's missing/wrong?

Cheers!

Update: I'm on Mac OS X Snow Leopard and I tried the same script using ruby 1.8.7 (system default) and 1.9.2 (Installed using RVM). I also tried the following:

f = File.open(path_js,'rb')
js = f.read
f.close
new_js = Iconv.conv('utf-8', 'utf-16', js)
File.open(path_new_js,'w'){|f| f.write(new_js)}

With the same outcome :S

1条回答
We Are One
2楼-- · 2019-08-07 13:48

That should be the equivalent of running the command directly, so be sure it's actually running correctly. system will return false if there's an error in execution.

You can also use the iconv library in Ruby to do it directly instead of needing the command line tool. That may offer more control.

查看更多
登录 后发表回答