samayres1992
samayres1992

Reputation: 779

Store Arrays as Hash?

I'm pulling CSV data then storing it as arrays. I need to return these arrays as a single Hash.

This will allow me to use a key for each index, instead of using the index number, but I'm having issues getting it to work. It logs an error saying there is the wrong number of arguments.

Any ideas where I'm going wrong?

Code:

ref       = Array.new
summary   = Array.new
pri       = Array.new
state     = Array.new
estdur    = Array.new
notes     = Array.new
supporter = Array.new
bz        = Array.new
project   = Array.new
team      = Array.new

hashed = Hash.new

csvPath = "#{File.dirname(__FILE__)}"+"/../modules/csv.csv"
CSV.foreach(csvPath, :headers=>true, :header_converters=>:symbol) do |row|
  ref       << row [ :feature   ]
  summary   << row [ :Summary   ]
  pri       << row [ :Pri       ]
  state     << row [ :State     ]
  estdur    << row [ :EstDur    ]
  notes     << row [ :Notes     ]
  supporter << row [ :Supporter ]
  bz        << row [ :BZ        ]
  project   << row [ :Project   ]
  team      << row [ :Team      ]
end
return hashed[
  "ref",       ref,
  "summary",   summary,
  "pri",       pri,
  "state",     state,
  "estDur",    estdur,
  "notes",     notes,
  "supporter", supporter,
  "bz",        bz,
  "project",   project,
  "team",      team
]

Upvotes: 1

Views: 459

Answers (2)

tadman
tadman

Reputation: 211740

The way you're going about this is rather confused. Any time you see a large number of variables like that is a sign you should be using a different storage method. That you collapse these into a Hash before returning them is a hint as to how they should be stored in the first place.

Here's a re-working that's much more Ruby flavored:

# Create a Hash where the default is an empty Array
result = Hash.new { |h, k| h[k] = [ ] }

# Create a mapping table that defaults to the downcase version of the key
mapping = Hash.new { |h, k| h[k] = k.to_s.downcase.to_sym }

# Over-ride certain keys that don't follow the default mapping
mapping[:feature] = :ref

csvPath = File.expand_path("/../modules/csv.csv", File.dirname(__FILE__))

CSV.foreach(csvPath, :headers => true, :header_converters => :symbol) do |row|
  row.each do |column, value|
    # Append values to the array under the re-mapped key
    result[mapping[column]] << value
  end
end

# Return the resulting hash
result

Upvotes: 7

Matzi
Matzi

Reputation: 13925

Use this:

return Hash["ref", ref, "summary", summary, "pri", pri, "state", state, 
            "estDur", estdur, "notes", notes, "supporter", supporter, 
            "bz", bz, "project", project, "team", team]

No need for hashed variable.

Upvotes: 4

Related Questions