2010-09-11 103 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 

请报到的代码:)

任何成功
相关问题