开发者

Return result of block passed to #scan during regex

I've searched and not been able to find the right way of doing what I'm trying to. I read a file开发者_StackOverflow line by line and want to create a new object from a regex on each line. I'm not using an XML parser because the data is not well formed and listed below is all I need to get from each line.

I can't seem to get scan to return the result of the block. It just returns the original string. I have temporarily gotten around it by creating this temp variable, but I'm sure there is a better way.

enum = File.foreach(filename)  

enum.map do |line|
   temp = nil
   line.scan(/<cab id="(\w+)" updates="(\d+)"/) { |a,b| temp = Cab.new(a,b) }
   temp
end

Thanks for any help.


I would do:

enum.map {|line| Cab.new(*line.match(/<cab id="(\w+)" updates="(\d+)"/)[1,2]) }

or if I wanted it to be more readable:

enum.map {|line|
  line =~ /<cab id="(\w+)" updates="(\d+)"/
  Cab.new($1, $2)
}


scan + map maybe?

line.scan(/<cab id="(\w+)" updates="(\d+)"/).map { |a,b| Cab.new(a,b) }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜