Ruby Array Loop

时间:2013-12-02 07:56:21

标签: ruby arrays loops

我目前正在尝试创建一个ruby算法来执行以下操作:

l = Array.new

给定数组是数组形式的文本,并且有三个清单,每个清单分别标题为第1节,第2节,第3节。

  1. 通过遍历数组(l)将整个文本放在一个字符串中,每次都将每行添加到一个大字符串中。

  2. 使用split方法和关键字“Section No.”拆分字符串这将创建一个数组,每个元素都是文本的一部分。

  3. 循环遍历此新数组,为每个元素创建文件。

  4. 到目前为止,我有以下内容:

    a = l.join ''
    b = Array.new
    b = a.split ("Section No.")`
    

    我如何将最简单的方法写入第三部分? 应该只有2-3行。

    输出将创建三个文件,每个文件以清单标题命名。

    “复杂版本”

    file_name = "Section" 
    section_number = "1"
    
    new_text = File.open(file_name + section_number, 'w')
    i = 0 
    n= 1
    while i < l.length 
        if (l[i]!= "SECTION") and (l[i+1]!= "No")
        new_text.puts l[i]
        i = i + 1
        else 
            new_text.close
            section_number = (section_number.to_i +1).to_s
            new_text = File.open(file_name + section_number, "w")
            new_text.puts(l[i])
            new_text.puts(l[i+1])
            i=i+2
        end
    end
    

3 个答案:

答案 0 :(得分:0)

要回答你最基本的问题,你可能会逃脱:

sections.each_with_index do |section, index|
  File.open("section_#{index}.txt", 'w') { |file| file.print section }
end

这是另一种解决方案:

input_string = "This should be your manifest string"
starting_string = "Section No."
copy_input_string = input_string.clone
sections = []
while(copy_input_string.length > 0)
  index_of_next_start = copy_input_string.index(starting_string, starting_string.length) || copy_input_string.length
  sections.push(copy_input_string.slice!(0...index_of_next_start))
end
sections.each_with_index do |section, index|
  File.open("section_#{index}.txt", 'w') { |file| file.print section }
end

答案 1 :(得分:0)

b.each_with_index(1) do |text, index|
  File.write "section_#{index}.txt", text
end

答案 2 :(得分:0)

通过在l

中的每个字符串之间放置一个空格来创建字符串
s = l.join ' '

拆分'节号' - 请注意'章节号'

中不再出现
a = s.split('Section No.')

在第一部分之前扔掉部分

a = a[1..-1]

创建文件

a.each do |section|
  File.open('Section' + section.strip[0], 'w') do |file_handle|
    file_handle.puts section
  end
end