gpt4 book ai didi

Ruby 不会在 puts 上转义 oct

转载 作者:数据小太阳 更新时间:2023-10-29 08:49:40 25 4
gpt4 key购买 nike

我有一个脚本可以解析一个大文本文件,提取某些值(使用 line.split),并将它们存储在一个文本文件中。我在将八进制值保存到文件时无法解释时遇到问题。

当我手动指定 oct 字符的 string 时,它工作正常:

test = "\320\232\320\250\320\220"

puts test

但是,如果我使用 title = line.split('=')[1] 获取上面的字符串,字符串值是相同的,但是当我尝试 puts,它只是重新陈述整个字符串(包括引号)

我做错了什么?

最佳答案

@xaxxon 解释了为什么当您从文件中读取字符串而不是将它们呈现为 ruby​​ 文字时,您的八进制代码没有被转换。这是将八进制\xxx 编码子字符串转换为适当的 ascii 字符的简单方法。

def octal_convert(s)
s.gsub(/\\(?:\\|[0-7]{3})/) do |capture|
capture == "\\\\" ?
"\\" :
capture[1,3].to_i(8).chr
end
end

test = 'ab\\\\cd\320\232\320\250\320\220'
=> "ab\\\\cd\\320\\232\\320\\250\\320\\220"
octal_convert(test)
=> "ab\\cd\xD0\x9A\xD0\xA8\xD0\x90"

关于Ruby 不会在 puts 上转义 oct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16370153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com