【问题标题】:Ruby splitting string into different filesRuby 将字符串拆分为不同的文件
【发布时间】:2013-12-18 14:35:30
【问题描述】:

在这里,我创建了一个算法,该算法可以提取一系列联邦党人文件并将它们拆分并保存到名为“联邦党人编号”的单独文件中。其次是各自的编号。一切正常,文件创建精美;但是,我现在遇到的唯一问题是它无法创建最后一个输出。 也许是因为我已经盯着这个看太久了,但我陷入了僵局。 我插入了puts fedSections.length 行来查看输出是什么。 使用美联储文件汇编的较小版本进行测试,终端输出为 3... 它创建“Federalist No. 0”一个空白文档以考虑空白空间和“Federalist No. 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

【问题讨论】:

  • 你的输入文件是什么?另外,为什么不使用each 循环而不是for
  • 输入文件列在与数组相同的 ruby​​ 程序中。 l = Array.new 然后接下来的几百行就是文本的行数。
  • 你可以从fedSections = []开始,然后在你的for循环中,做fedSections.push "Federalist No. #{f}"——查找Ruby的字符串插值,而不是构建一个字符串,然后用fedString.split创建一个数组规则以获取有关其工作原理的更多信息。

标签: ruby arrays string substring


【解决方案1】:

错误在你的 for 循环中

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

你真的想要

for k in 0..fedSections.length-1

... 不包括范围内的最后一个元素

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

fedSections.each do |section|

【讨论】:

  • 应该使用each
  • 是的!太感谢了。我不敢相信只是一个点让我卡了好几个小时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
相关资源
最近更新 更多