【问题标题】:Writing Unix line breaks on Windows with JRuby使用 JRuby 在 Windows 上编写 Unix 换行符
【发布时间】:2011-12-25 05:41:40
【问题描述】:

我正在编写一个 Ruby 脚本来生成一个 Unix shell 脚本,但我无法让 JRuby 在 Windows 上编写 Unix 换行符。

我写了一个文件test.rb,其中包含:

File.open("test.sh", 'w') do |f|
  f.write("#!/bin/sh\n")
  f.write("echo hello\n")
end

当我使用命令java -jar jruby-complete-1.6.5.jar test.rb 执行它时,生成的文件包含\r\n 换行符而不是\n 换行符。

如何强制 JRuby 编写带有 Unix 换行符的文本文件?

【问题讨论】:

  • 试过文件顶部的神奇评论# encoding: utf-8-unix
  • # encoding: utf-8-unix 没有帮助。

标签: ruby windows unix jruby newline


【解决方案1】:

我设法通过在File.open 的参数中添加“b”来修复它

File.open("test.sh", 'wb') do |f|
  f.write("#!/bin/sh\n")
  f.write("echo hello\n")
end

IO class 的文档对此进行了如下说明:

Mode |  Meaning
-----+--------------------------------------------------------
 "b" |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------

【讨论】:

    猜你喜欢
    • 2010-10-17
    • 1970-01-01
    • 2011-02-01
    • 2014-11-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多