2016-11-04 18 views
0

我需要写一个识别部分文字红宝石 - 我需要每下一次迭代作为我的方法参数

lines.each do |line| 
    case line.match 
    when :chapter 
     chapter = analyze_chapter(line) 
     previous = chapter 
    when :section 
     section = analyze_section(line) 
     previous.sections<< section 
     previous = section 
    end 
    end 

等,针对不同的元素代码。的analyze_chapter 例子:

def analyze_chapter(chapter_line) 
    Chapter.new(
    title: chapter_line.title, 
    sections: [analyze_section(chapter_line)] 
    )  
end 

问题是我的输入是这样的:

Chapter 1 - name 
Section 1 - name 

我的代码是如何工作的:我使用正则表达式来识别标题的模式。然后,我把这个匹配的标题保存为Line对象的title属性。 它工作正常,在我不同的代码,我在那里认识

Chapter 1 - name, Rest of the text - everything in one line 

但很明显,现在我需要下一行传递给sections[analyze_sections(chapter_line)] - 我种需要下一次迭代,因为Chapter titleSection title不是一条线。 我知道这可能是一些逻辑错误。我会很感激任何帮助。

+0

是'analyze_section'和'analyze_sections'应该是同一个方法吗?是属于那一章的章节之后的所有章节? – SteveTurczyn

+0

是的,这是一个错字。是的,章节之后的每个章节都属于它 - 直到下一章出现。 – Jes

回答

1

这似乎你非常接近你想要的......这会给你一个章节对象的数组,每个对象包括一个ar光线的部分。

chapters = [] 
lines.each do |line| 
    case line.match 
    when :chapter 
     chapters << analyze_chapter(line) 
    when :section 
     chapters.last.sections << analyze_section(line) 
    end 
    end 
end 

唯一潜在的问题是,如果第一行是:section没有前面的:chapter ...如果这是不可能的这是不是你需要的代码的东西,如果是,你可能需要一个方法这将创建一个“无标题”章节。

chapters = [] 
lines.each do |line| 
    case line.match 
    when :chapter 
     chapters << analyze_chapter(line) 
    when :section 
     chapters << create_missing_chapter if chapters.empty? 
     chapters.last.sections << analyze_section(line) 
    end 
    end 
end 

def create_missing_chapter 
    Chapter.new(
    title: "My First Chapter", 
    sections: [] 
    ) 
end 
1

不必一次创建所有章节的章节,而必须创建一个带有空白章节数组的章节并在之后进行填充。是这样的:

require 'ostruct' 
Chapter = Section = OpenStruct # <- just for demonstration purposes 

lines = <<-TEXT.split("\n") 
Chapter 1 - Recurrent Problems 
Section 1 - The Tower of Hanoi 
Section 2 - Lines in the Plane 
Section 3 - The Josephus Problem 
TEXT 

chapters = [] 
lines.each do |line| 
    case line 
    when /^Chapter (\d+) - (.+)$/ 
    chapters << Chapter.new(number: $1, title: $2, sections: []) 
    when /^Section (\d+) - (.+)$/ 
    chapters.last.sections << Section.new(number: $1, title: $2) 
    end 
end 

上述填充一个chapters阵列Chapter情况下,每个具有含Section实例一个sections阵列属性:

chapters.each do |chapter| 
    puts "#{chapter.number} #{chapter.title}" 
    chapter.sections.each do |section| 
    puts " #{chapter.number}.#{section.number} #{section.title}" 
    end 
end 

输出:

1 Recurrent Problems 
    1.1 The Tower of Hanoi 
    1.2 Lines in the Plane 
    1.3 The Josephus Problem