Specify starting point of foreach enumerator in ruby

≡放荡痞女 提交于 2019-12-11 02:59:07

问题


I have a rake file that pulls in data from an external CSV file and enumerates through it with:

CSV.foreach(file, :headers => true) do |row|

What is the most effective way (in ruby) to specify the starting point within the spreadsheet?

:headers => true allows me to start importing from the second line, but what if I want to start a line 20?


回答1:


Use .drop(#rows to ignore):

CSV.open(file, :headers => true).drop(20).each do |row|




回答2:


Ruby enumerators include a drop method that will skip over the first n items.

When not passed a block, CSV.foreach returns an enumerator.

You can use

CSV.foreach(file, :headers => true).drop(20).each do |row|

This will skip the first 20 data rows (the header row does NOT count as one of those twenty).



来源:https://stackoverflow.com/questions/22898317/specify-starting-point-of-foreach-enumerator-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!