Hoopla!

now with extra whiz-bang!

Hoopla!

Ruby: Parsing CSV files quickly

August 03, 2006 · 6 comments

I seem to have a limitless stream of excel files coming at me from clients. Most of them are of the same format: first line is the column name and the rest of the lines are data.

Ruby has excellent baked-in capabilities for handling files, data, and even CSV stuff. Still, it was pretty hard for me to figure out how to turn a CSV file into an array of hashes where each cell was named with the correct column name.

So here y’are folks: an easy way to turn CSV files into an array of hashes.

def csv_to_array(file_location)
  csv = CSV::parse(File.open(file_location, 'r') {|f| f.read })
  fields = csv.shift
  csv.collect { |record| Hash[*(0..(fields.length - 1)).collect {|index| [fields[index],record[index].to_s] }.flatten ] }
end

→ 6 comments Tags:

States with abbreviations

June 12, 2006 · 2 comments

Sometimes it’s hard to come by this list when you need it. Hope this saves somebody some time. Here are the 50 states with their two-letter abbreviations in a Ruby-formatted array.
1
2
3
4
5
6
7
8
9
10
11
[ ["ALABAMA","AL"],
  ["ALASKA","AK"],
  ["AMERICAN SAMOA","AS"],
  ["ARIZONA ","AZ"],
  ["ARKANSAS","AR"],
  ["CALIFORNIA ","CA"],
  ["COLORADO ","CO"],
  ["CONNECTICUT","CT"],
  ["DELAWARE","DE"],
  ["DISTRICT OF COLUMBIA","DC"],
  ["FEDERATED STATES OF MICRONESIA","FM"],
  ["FLORIDA","FL"],
  ["GEORGIA","GA"],
  ["GUAM","GU"],
  ["HAWAII","HI"],
  ["IDAHO","ID"],
  ["ILLINOIS","IL"],
  ["INDIANA","IN"],
  ["IOWA","IA"],
  ["KANSAS","KS"],
  ["KENTUCKY","KY"],
  ["LOUISIANA","LA"],
  ["MAINE","ME"],
  ["MARSHALL ISLANDS","MH"],
  ["MARYLAND","MD"],
  ["MASSACHUSETTS","MA"],
  ["MICHIGAN","MI"],
  ["MINNESOTA","MN"],
  ["MISSISSIPPI","MS"],
  ["MISSOURI","MO"],
  ["MONTANA","MT"],
  ["NEBRASKA","NE"],
  ["NEVADA","NV"],
  ["NEW HAMPSHIRE","NH"],
  ["NEW JERSEY","NJ"],
  ["NEW MEXICO","NM"],
  ["NEW YORK","NY"],
  ["NORTH CAROLINA","NC"],
  ["NORTH DAKOTA","ND"],
  ["NORTHERN MARIANA ISLANDS","MP"],
  ["OHIO","OH"],
  ["OKLAHOMA","OK"],
  ["OREGON","OR"],
  ["PALAU","PW"],
  ["PENNSYLVANIA","PA"],
  ["PUERTO RICO","PR"],
  ["RHODE ISLAND","RI"],
  ["SOUTH CAROLINA","SC"],
  ["SOUTH DAKOTA","SD"],
  ["TENNESSEE","TN"],
  ["TEXAS","TX"],
  ["UTAH","UT"],
  ["VERMONT","VT"],
  ["VIRGIN ISLANDS","VI"],
  ["VIRGINIA ","VA"],
  ["WASHINGTON","WA"],
  ["WEST VIRGINIA","WV"],
  ["WISCONSIN","WI"],
  ["WYOMING","WY"] ]

→ 2 comments Tags: