Ruby将字符串拆分成不同的文件

时间:2013-12-02 19:04:51

标签: ruby arrays string substring

在这里,我创建了一个算法,提取联邦主义者论文的数组并将它们分开,将它们保存到标题为“联邦党人号”的单独文件中。其次是各自的数字。一切都很完美,文件创造得很漂亮;但是,我遇到的唯一问题是它无法创建最后一个输出。 也许是因为我已经盯着这个太多时间,但我陷入了僵局。 我已插入行puts fedSections.length以查看输出结果。 使用较小版本的美联储论文汇编进行测试,终端输出为3 ...它创建了“联邦党人0号”空白文件以考虑空白空间和“联邦党人1号”与第一联邦主义者纸。没有“联邦党人2号”。

有什么想法吗?

# Create new string to add array l to 
fedString = " "


for f in 0...l.length-1 
    fedString += l[f] + ''
end

# Create variables applied to new files

Federalist_No= "Federalist No." 
a = "0"
b = "FEDERALIST No."    


fedSections = Array.new() # New array to insert Federalist paper to 
fedSections = fedString.split("FEDERALIST No.")  # Split string into elements of the array at each change in Federalist paper
puts fedSections.length

# Split gives empty string, off by one

for k in 0...fedSections.length-1 # Use of loop to write each Fed paper to its own file
    new_text = File.open(Federalist_No + a + ".txt", "w") # Open said file with write capabilities
    new_text.puts(b+a) # Write the "FEDERALIST No" and the number from "a"
    new_text.puts fedSections[k] # Write contents of string (section of paper) to a file
    new_text.close()
a = a.to_i + 1 # Increment "a" by one to accomodate for consecutive papers 
a = a.to_s # Restore to string

end

1 个答案:

答案 0 :(得分:0)

错误在你的for循环中

for k in 0...fedSections.length-1

你真的想要

for k in 0..fedSections.length-1

...不包括范围

中的最后一个元素

但正如screenmutt所说,使用each循环是更惯用的红宝石

fedSections.each do |section|
相关问题