You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows环境下如何在Ruby中以不同编码(如ANSI)保存文件

在Windows下用Ruby以ANSI编码保存文件

在Windows下用Ruby实现以ANSI编码保存文件其实很简单,不过得先明确一点:ANSI并不是一个单一的编码标准,它在不同语言的Windows系统里对应不同的系统默认代码页——比如英文系统常用CP1252,中文系统则是GBK(也叫CP936)。

下面给你两种实用的实现方式:

  • 直接在文件打开模式中指定编码
    你可以在File.open的模式参数里通过模式:编码的格式指定目标编码,这种方式简洁直观,而且块式写法能自动帮你关闭文件,比手动调用close更安全:

    # 英文Windows系统(ANSI对应CP1252)
    File.open("c:/ruby/hps.txt", "w:Windows-1252") do |file|
      file.puts 'there is some text'
    end
    
    # 中文Windows系统(ANSI对应GBK/CP936)
    File.open("c:/ruby/hps.txt", "w:GBK") do |file|
      file.puts 'there is some text'
    end
    
  • 通过Encoding类指定编码
    如果你需要更灵活地处理编码(比如动态选择编码),可以用Encoding.find获取对应编码对象,再传入encoding参数:

    # 根据你的系统替换成对应的编码名称,比如'Windows-1252'或'GBK'
    target_encoding = Encoding.find('GBK')
    
    File.open("c:/ruby/hps.txt", "w", encoding: target_encoding) do |file|
      file.puts 'there is some text'
    end
    

如果你不确定自己系统的ANSI对应哪种编码,可以在命令提示符里输入chcp命令查看代码页:比如中文系统会显示活动代码页: 936,对应的编码就是GBK;英文系统通常是1252,对应Windows-1252。

内容的提问来源于stack exchange,提问作者Kamran Sofla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 06:07:29