如何实际为字符串写一个换行符

时间:2015-03-31 22:02:25

标签: ruby string-substitution

我该如何制作

content[i].gsub("\n", "\\n")

将(写成类似的)写入文件

str = "some text\n"

我正在编写一段代码来获取文件并构建一个单独的字符串,可以将其插回到您正在使用的源代码中,如果这有用的话

如果我弄错了,我的错误实际上是代码中的其他地方,这里是:

#!/bin/usr/ruby
#reads a file and parses into a single string declaration in language of choice
#another little snippet to make my job easier when writing lots of code
#programmed by michael ward
# h3xc0ntr0l@gmail.com | gists.github.com/michaelfward


# ***************************************
#              example scrips
#  with writefiles 
#   | writefiles [file with paths] [file to write*]
#   | makestring [file to write* (actually is read, but same as above)] [lang] 
#****************************************


def readFile(path)
  fd = File.open(path, "r")
  content = []
  fd.each_line {|x| content.push(x)}
  content = fixnewlines(content)
  str = content.join()
  str
end

def fixnewlines(content)
  content.each_index do |i|
    content[i].gsub("\n", "\\n")
  end
end

def usage
  puts "makestring [file to read] [language output]"
  exit
end

langs = {"rb"=>"str =", "js" => "var str =", "c"=> "char str[] ="}

usage unless ARGV.length == 2
lang = ARGV[1]
path = ARGV[0]
str = readFile(path)
if langs[lang] == nil
  if lang == "c++" || lang == "cpp" || lang == "c#"
    puts "#{lang[c]}#{str}"
  else
    puts "unrecognized language found. supported languages are"
    langs.each_key {|k| puts "   #{k}"}
    exit
  end
else
  puts "#{langs[lang]} #{str}"
end

2 个答案:

答案 0 :(得分:0)

这取决于您使用的平台。 Unix使用\n作为行结束字符,而Windows使用\r\n。看起来你正在用\\n取代所有新的行字符,这些字符会转移我不希望在任何平台上工作的新行字符。

答案 1 :(得分:0)

只需删除fixnewlines并更改readFile

def readFile(path)
  File.read(path).gsub("\n", '\n')
end

希望它有所帮助。在Windows上使用\r\n而不是\n。没有必要在单个括号内转义斜杠。