tags:

views:

62

answers:

1

Hey everyone,

I have a quick question on retrieving information from a hash, here is the code thus far:

permits_sheet.each do |row|
  rate_type = row[0].to_s #Converts the rate type (title) to a string
  row.shift #Removes the title from hash so it's not added to values
  row.each do |values|
    split_value = values.split ('=') #References relations from an excel sheet pulled in earlier. EG: T=2324, W=8633
    (@@permits_hash[rate_type] ||= []) << {split_value[0].to_s => split_value[1]} #Multiple values exist within each title
  end
end

puts @@permits_hash['R']['T'] #In this example I'm searching for the hash key of T under the R title. I expected it to return the 2324 from the example above.

When attempting to retrieve information in this manner it results in an error. I'm sure I just did something stupid, but any help would be greatly appreciated (haven't used Ruby in quite awhile).

Thanks for the help!

+2  A: 

How about not storing your hashes in an array but instead like a nested hash?

(@@permits_hash[rate_type] ||= {})[split_value[0].to_s]=split_value[1]]

Not that it helps readability but I actually think you can write the two loops as a one-liner.

@@permits_hash=Hash.new 
row=["title","k1=v2","k2=v2","k3=v3"]
# Here's the line replacing the two loops  
(@@permits_hash[row.shift] ||= {}).update(Hash[*row.map{|v| v.split("=")}.flatten])

>> @@permits_hash
=> {"title"=>{"k1"=>"v2", "k2"=>"v2", "k3"=>"v3"}}

Jonas Elfström
You sir, are a gentleman and a scholar. That is exactly what I've been looking for, but I've been staring at the screen so long I just couldn't remember how to do it correctly.Thanks once again for the help!
Ruby Novice
Thanks, also added a one-liner.
Jonas Elfström
@Ruby Novice: if Jonas solved your problem (as it appears) it would be nice for you to accept his answer by clicking the check mark to the left of the answer.
JacobM