2014-03-03 55 views
0

我做一些CSV處理用下面的代碼...優雅的方式來處理在CSV處理stripeme中的零?

CSV.foreach(file.tempfile, :headers => true) do |row| 
     students[row["person_id"]]["start_dates"] << Date.strptime(row["start_date"], '%m/%d/%Y') 
     students[row["person_id"]]["end_dates"] << Date.strptime(row["end_date"], '%m/%d/%Y') 
    end 

不過,我的一些細胞都在我的csv文件的空白,我的Date.strptime與「失敗不能零轉換成字符串」。處理這個問題的最好/最優雅的方法是什麼?

我希望的東西,簡潔的喜歡...

students[row["person_id"]]["last_attend_dates"] << Date.strptime(row["last_attend_date"], '%m/%d/%Y') || "" 

...但是Ruby沒有LIKEY。

+0

使用https://github.com/tilo/smarter_csv它可以輕鬆解決您的所有問題。 –

+0

'Date.strptime(row [「last_attend_date」],'%m /%d /%Y')|| 「'''不會工作,因爲它在你到達||之前通過了nil來引起異常(導致異常) 「」'。最接近的語法是'(Date.strptime(row [「last_attend_date」],'%m /%d /%Y')rescue「」)'但是使用像這樣的救援在我看來有點髒。 –

回答

1

木箱自定義轉換如下:

CSV::Converters[:custom] = lambda do |s| 
    Date.strptime(row["last_attend_date"], '%m/%d/%Y') unless s.nil? 
end 

然後做如下:

CSV.foreach(file.tempfile, :headers => true, :converters => [:custom]) do |row| .. 

參見文檔Converters也。

+0

其實只要在當前的代碼中加入'除非'似乎可以正常工作。請參閱http://pastie.org/8843313。對我來說似乎更簡單。我是否通過做這樣的事情來打開自己? – Lumbee

+0

@Lumbee你爲什麼要在外面處理它,而不是在CSV解析時處理它。 CSV給你的設施,所以使用它。 :-) –

相關問題