2014-04-14 95 views
0
lines = ["title= flippers dippers track= 9", "title= beaner bounce house track= 3", "title= fruit jams live track= 12"] 
songs_formatted = [] 
songs = {} 

lines.each do |line| 
    line =~ /title=\s?(.*)\s+t/ 
    title = "#$1".strip 
    songs[:title] = title 

    line =~ /track=\s?(.*)/ 
    track = "#$1".strip 
    songs[:track] = track 

    songs_formatted << songs 
end 

p songs_formatted 

#=> [{:title=>"flippers dippers", :track=>"9"}] 
#=> [{:title=>"beaner bounce house", :track=>"3"}, {:title=>"beaner bounce house", :track=>"3"}] 
#=> [{:title=>"fruit jams live", :track=>"12"}, {:title=>"fruit jams live", :track=>"12"}, {:title=>"fruit jams live", :track=>"12"}] 

每個連續的行覆蓋之前的行。爲什麼這不是按順序追加的?期望的結果是:如何將散列追加到數組?

songs_formatted = [{:title=>"flippers dippers", :track=>"9"}, {:title=>"beaner bounce house", :track=>"3"}, {:title=>"fruit jams live", :track=>"12"}] 

回答

2

需要將songs散放在每個循環內。工作代碼:

lines = ["title= flippers dippers track= 9", "title= beaner bounce house track= 3", "title= fruit jams live track= 12"] 
songs_formatted = [] 

lines.each do |line| 
    songs = {} 

    line =~ /title=\s?(.*)\s+t/ 
    title = "#$1".strip 
    songs[:title] = title 

    line =~ /track=\s?(.*)/ 
    track = "#$1".strip 
    songs[:track] = track 

    songs_formatted << songs 
end 

p songs_formatted 

正確的輸出:

#=> [{:title=>"flippers dippers", :track=>"9"}, {:title=>"beaner bounce house", :track=>"3"}, {:title=>"fruit jams live", :track=>"12"}] 
0

既然你想每行一個輸出,可以使用map。此外,你可以提取一個正則表達式。

lines.map do |line| 
    title, track = line.match(/title=\s?(.*?)\s*track=\s?(\d+)/)[1,2] 
    {title: title, track: track} 
end 

這給你你想要的輸出。