Archive for the ‘ruby’ Category

ruby csv to structured hash

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[ [...]

September 18, 2008 • Posted in: rails, ruby • No Comments

Ruby conversion module

This is a ruby module useful for conversions dealing with length, weight, torque.
module Convert

  def Convert.number_with_precision(number, precision=2)
    “%01.#{precision}f” % number
  rescue
    number
  end

  def Convert.mm_to_in(mm, precision=2)
    number_with_precision(mm * 0.03937, precision)
  end

  def Convert.in_to_mm(inches, precision=2)
    number_with_precision(inches / 0.03937 , precision)
  end

  def Convert.feet_to_meters(f, precision=2)
    number_with_precision( f * 0.3048, precision)
  end

  def Convert.meters_to_inches(m, precision=2)
    number_with_precision( m * [...]

July 2, 2008 • Posted in: rails, ruby • No Comments