2013-11-03 117 views
1

假設我有以下內容的字符串:如何閱讀格式化文本?

TODO | Eat spaghetti.    | High | food, happiness 
TODO | Get 8 hours of sleep.  | Low | health 
CURRENT | Party animal.    | Normal | socialization 
CURRENT | Grok Ruby.     | High | development, ruby 
DONE | Have some tea.    | Normal | 
TODO | Destroy Facebook and Google. | High | save humanity, conspiracy 
TODO | Hunt saber-toothed cats.  | Low | wtf 
DONE | Do the 5th Ruby challenge. | High | ruby course, FMI, development, ruby 
TODO | Find missing socks.   | Low | 
CURRENT | Grow epic mustache.   | High | sex appeal 

什麼是閱讀這些內容,並將其存儲的最佳方式中的對象結構如下說:

class example 
    attr_accessor status 
    attr_accessor description 
    attr_accessor priority 
    attr_accessor tags 
end 

我與嘗試以下的正則表達式:

/[a-zA-Z0-9]*/.match(text above) 

但我得到的是

#<MatchData "TODO"> 

我希望得到的是

[TODO, Eat spaghetti, High, food, happiness, TODO ... etc ] 

什麼是實現這一目標的最佳方式是什麼?

+0

只要分割線與'|'和剝離它。 – zishe

回答

0

"TODO | Eat spaghetti. | High | food, happiness".split('|')

=> ["TODO ", " Eat spaghetti.    ", " High ", " food, happiness"] 

OR

"TODO | Eat spaghetti.    | High | food, happiness".scan(/[^|]+/) 

=> ["TODO ", " Eat spaghetti.    ", " High ", " food, happiness"] 

OR

"TODO | Eat spaghetti.    | High | food, happiness".split('|').map{ |i| i.strip } 
=> ["TODO", "Eat spaghetti.", "High", "food, happiness"] 
0
text.each_line.map{|l| l.strip.split(/\s*\|\s*/)} 

結果:

[ 
    ["TODO", "Eat spaghetti.", "High", "food, happiness"], 
    ["TODO", "Get 8 hours of sleep.", "Low", "health"], 
    ["CURRENT", "Party animal.", "Normal", "socialization"], 
    ["CURRENT", "Grok Ruby.", "High", "development, ruby"], 
    ["DONE", "Have some tea.", "Normal"], 
    [ 
    "TODO", 
    "Destroy Facebook and Google.", 
    "High", 
    "save humanity, conspiracy" 
    ], 
    ["TODO", "Hunt saber-toothed cats.", "Low", "wtf"], 
    [ 
    "DONE", 
    "Do the 5th Ruby challenge.", 
    "High", 
    "ruby course, FMI, development, ruby" 
    ], 
    ["TODO", "Find missing socks.", "Low"], 
    ["CURRENT", "Grow epic mustache.", "High", "sex appeal"] 
] 
0

爲了獲取數據到類,我們需要4個步驟:

首先獲得內存中的數據:

file = 'path/to/my/file.txt' 
raw_data = File.read(file) 

採取分析數據每行都用|分割然後去掉空白處和新行。

parsed_data = raw_data.lines.map{|line| line.split('|').map(&:strip)} 
p parsed_data.first #=> ["TODO", "Eat spaghetti.", "High", "food, happiness"] 

定義類示例:

class Example 
    attr_accessor :status, :description :priority, :tags 

    def initialize(status, description, priority, tags) 
    @status, @description, @priority = status, description, priority 
    @tags = tags.split(', ') # Split tags and store in a list. 
    end 

end 

創建新的對象:

list_of_examples = parsed_data.map{|line| Example.new(*line)} 
p list_of_examples.first #=> #<Example:0x2212ae8 @priority="High", @description="Eat spaghetti.", @status="TODO", @tags=["food", "happiness"]>