2015-03-31 42 views
0

我怎樣才能讓這個如何實際編寫一個換行符爲一個字符串

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 
+1

Ruby約定是對變量和方法的名稱使用「蛇形」(小寫字母,數字和下劃線),所以你通常會看到你的方法'readFile'寫入'read_file'。你不必這樣做,但是你會看到99%的Ruby代碼遵循這個約定。 – 2015-04-01 00:35:11

+1

我建議你在codereview.stackexchange.com上發佈這篇文章,你會得到很好的建議,說明如何使它更清晰,簡潔和rubylike。 – 2015-04-01 01:22:56

+0

@MarkThomas [codereview.se]預計發佈的代碼將按預期工作。其他一切(包括這一點,似乎)都被認爲是無關緊要的。 – nhgrif 2015-04-01 01:24:57

回答

0

只是刪除fixnewlines和改變readFile

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

希望它能幫助。在Windows上使用\r\n而不是\n。沒有必要在單個括號內跳出斜槓。

+0

工作就像一個魅力。謝謝! – h3xc0ntr0l 2015-03-31 22:19:57

0

這取決於您使用的平臺。 Unix使用\n作爲行尾字符,而Windows使用\r\n。它看起來像你正在替換所有新的行字符,但\\n逃脫了新的行字符,我不希望在任何平臺上工作。

+0

嗨;感謝那!我有點想到它跟我寫字符串的方式有關(因爲我意識到我正在逃避我的逃跑,寫'\',接着是'n',導致\ n分析一個新行)。我的問題實際上更多的是如何寫一個\ n到一個文件(或標準輸出,沒關係,但我認爲它會是相同的任何方式),而不會導致一個新行被解析。 – h3xc0ntr0l 2015-03-31 22:17:27

相關問題