2016-11-04 55 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