ruby - How can I print a string contained in an object as literal with Ruby?
问题描述
I'm trying to write a program which will detect if a file has \n
or \r\n
line endings and then fix them. I'm hoping to have the script output some messages to a console, but I'm running into trouble. I can't figure out how to print the line endings as literals.
Here is my method which checks for the line ending type:
def determine_line_ending(filename)
File.open(filename, 'r') do |file|
return file.readline[/\r?\n$/]
end
end
ending = determine_line_ending(ARGV.first)
Supposedly this method will return either \n
or \r\n
if it matches one of those patterns on the first line of the file.
I would like to then print to the console which ending type was detected but if I use puts ending
then it just adds a line ending to the console. I know that if I used puts '\r\n'
then it will print them literal, or if I use double quotes I just have to escape the backslashes. But I'm pretty new to Ruby and I'm having a hard time just finding a way to print my variable as a literal instead of a string.
解决方案
如果我理解你的话,如果行尾是 \r,你想打印“\r”字符串,如果 \r\n 则打印“\r\n”。
在这种情况下,您可以使用转储功能是您所需要的:
puts ending.dump // => "\r" or "\r\n"
推荐阅读
- docker - Docker`COPY`文件不起作用
- python-3.x - 逐行读取和分析输出数据
- batch-file - Sqlcmd 参数传递给 sql 脚本文件
- java - 如何制作自定义文本视图?
- c# - 使用 mshtml 和 shdocview vb.net/C# 捕获 Web 元素
- php - 在 Laravel-5 中取消定义方法?
- selenium - 在另一个选项卡中打开相同的 URL 时,Selenium 未显示活动会话被拒绝
- node.js - 在 ejs 模板中获取查询字符串
- c# - 授权 - .net 核心中的声明集
- amazon-web-services - Ruby AWS 开发工具包 (v2/v3) 标记 Spot 实例