2010-09-11 98 views
0

我想在特定的heredoc字符串後追加一個heredoc字符串,如果文件沒有包含它的話。如果文件不包含該heredoc字符串,在特定的heredoc字符串之後追加heredoc字符串?

例如,

這裏有2個文件:

# file1 
Description: 
    I am a coder 
Username: user1 
Password: password1 

# file2 
Description: 
    I am a coder 
Username: user2 
Password: password2 
Address: 
    Email: [email protected] 
    Street: user street 19 A 

我想補充:

Address: 
    Email: [email protected] 
    Street: user street 19 A 

如果文件不包含它已經和後:

Description: 
    I am a coder 

所以在上面的文件只會被添加到第一個文件中。然後該文件將如下所示:

# file1 
Description: 
    I am a coder 
Address: 
    Email: [email protected] 
    Street: user street 19 A 
Username: user1 
Password: password1 

我怎麼能在Ruby中做到這一點?

回答

1

這個問題沒有很好的闡述 - 你得到的概念「這裏的文檔」困惑。

我會留下一些代碼至極,我希望可以幫助你的任務,在某些方面

end_of_line_delimiter = "\n" 
file1_arr = File.read('file1.txt').split(end_of_line_delimiter) #Array of lines 
file1_has_address = file1_arr.index {|a_line| a_line =~ /^Address:/ } 

unless file1_has_address 
    #file1 does not contain "Address:" 
    #Build address_txt 
    email  = "[email protected]" 
    street  = "some street" 
    address_txt = <<END 
Address: 
    Email: #{email} 
    Street: #{street} 
END 
    #Insert address_txt 2 lines after the "Description:" line 
    description_line_index = file1_arr.index {|a_line| a_line =~ /^Description:/ } 
    raise "Trying to insert address, but 'Description:' line was not found!" unless description_line_index 
    insert_line_index = description_line_index + 2 
    file1_arr.insert(insert_line_index, *address_txt.split(end_of_line_delimiter)) 

end 

#file1_arr will now have any Address needed added 
file1_txt = file1_arr.join(end_of_line_delimiter) 

puts file1_txt 

請報到的代碼:)

任何成功
相關問題