2014-04-14 9 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 

이렇게하면 원하는 결과물을 얻을 수 있습니다.

관련 문제