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"}]
答案 0 :(得分: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"}]
答案 1 :(得分:0)
由于每行需要一个输出,因此可以使用map
。此外,您可以使用一个正则表达式提取两者。
lines.map do |line|
title, track = line.match(/title=\s?(.*?)\s*track=\s?(\d+)/)[1,2]
{title: title, track: track}
end
这可以为您提供所需的输出。