【问题标题】:Ruby Array LoopRuby 数组循环
【发布时间】:2013-12-17 20:49:56
【问题描述】:

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

l = Array.new

给定数组是数组形式的文本,具有三个清单,每个清单分别标题为 Section No. 1、Section No. 2、Section No. 3。

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

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

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

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

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

【问题讨论】:

    标签: ruby arrays loops


    【解决方案1】:
    b.each_with_index(1) do |text, index|
      File.write "section_#{index}.txt", text
    end
    

    【讨论】:

      【解决方案2】:

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

      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
      

      【讨论】:

      • 当您使用sections.each 时,您是从哪里获得部分的?我对Ruby很陌生。它是一种方法还是仅仅是因为我试图让“Section No”AKA 对任何事情都那么灵活?
      • 不,这正是我将变量 b 命名为以便描述内容的原因。
      • 所以在运行程序后,我只得到一个名为“Section_0”的文件,其中包含所有三个清单。知道如何调试吗?
      • puts b.size 会给你数组的大小。文件拆分是否实际上将文件划分为多个部分?
      • 它说 1 所以我假设没有。有没有更好的方法使用关键字将其拆分为多个部分?
      【解决方案3】:

      通过在 l 中的每个字符串之间放置一个空格来创建字符串 s

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多