首页 > 解决方案 > 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.

标签: rubystring-literalsline-endings

解决方案


如果我理解你的话,如果行尾是 \r,你想打印“\r”字符串,如果 \r\n 则打印“\r\n”。

在这种情况下,您可以使用转储功能是您所需要的:

puts ending.dump // => "\r" or "\r\n"

推荐阅读