我怎樣才能讓這個如何實際編寫一個換行符爲一個字符串
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
# [email protected] | 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
Ruby約定是對變量和方法的名稱使用「蛇形」(小寫字母,數字和下劃線),所以你通常會看到你的方法'readFile'寫入'read_file'。你不必這樣做,但是你會看到99%的Ruby代碼遵循這個約定。 – 2015-04-01 00:35:11
我建議你在codereview.stackexchange.com上發佈這篇文章,你會得到很好的建議,說明如何使它更清晰,簡潔和rubylike。 – 2015-04-01 01:22:56
@MarkThomas [codereview.se]預計發佈的代碼將按預期工作。其他一切(包括這一點,似乎)都被認爲是無關緊要的。 – nhgrif 2015-04-01 01:24:57