I had a csv like this:
| object | color | flavor | shape |
|---|---|---|---|
| apple | red | sweet | round |
| banana | yellow | sweet | long |
| lemon | yellow | sour | round |
and I wanted a ruby hash structured like this:
{
'apple'=> { 'color'=>'red', 'flavor'=>'sweet', 'shape'=>'round'},
'banana'=> { 'color'=>'yellow', 'flavor'=>'sweet', 'shape'=>'long'},
'lemon'=> { 'color'=>'yellow', 'flavor'=>'sour', 'shape'=>'round'}
}
So I wrote this, which does the job:
require "faster_csv"
def csv_to_structured_hash
arr_of_arrs = FasterCSV.read( 'your.csv' )
stuff = {}
header = arr_of_arrs.shift
arr_of_arrs.each_with_index do |row, i|
thing = { row[0] => {} }
header.each_with_index do |col, header_index|
thing[ row[0] ][ header[header_index] ] = row[ header_index]
end
stuff.update( thing )
end
return stuff
end
Ruby Duration
[download id="1" format="1"]
Duration.new recieves a string describing a duration of time, and converts it into: seconds, and a standard readable format.
Or, you can pass Duration.new an integer representing seconds, and receive the same standard readable format.
Usage:
Passing a String
duration = Duration.new("2weeks 8 hr 30m") duration.seconds # => 1240200 duration.readable # => "2 weeks, 8 hours and 30 mins"Passing an Fixnum (of seconds)
Example valid input strings
“2 weeks”, “2wks”, “2w”,
“8h”, “8 hrs”,”8 hours”,
“30m”, “0:30″, “30 minutes”, “30min”,
“2 weeks, 8 hours and 30 minutes”, “2w 8h 30m”, “2w 8:30″,
“4 hours 30 minutes”, “4 hours and 30m”, “4h 30min”, “4:30″, “4.5″, “4.50″, “4h, 30 min”, “4.5 hours”, “4.50h”
http://ahabman.com added functionallity, extended and mashed-up http://stackoverflow.com/questions/657309/how-to-parse-days-hours-minutes-seconds-in-ruby and http://www.postal-code.com/binarycode/2007/04/04/english-friendly-timespan/