Multidimensional dynamic Hash

OK I give up, how do I do this…

I have a DB that stores dynamic variables with I group into
group_id’s. For instance here are a couple examples of db rows:

title=“name”, description = “john”, grouping_id = “1”
title=“location”, description = “USA”, grouping_id = “1”
title=“comment”, description = “hello”, grouping_id = “1”

title=“name”, description = “frank”, grouping_id = “2”
title=“location”, description = “CA”, grouping_id = “2”
title=“comment”, description = “hi”, grouping_id = “2”

Sure I could create a DB with these columns, but for various reasons
I’m doing it this way.

SO, how do I store all this information in a hash? I want end up
looking something like this:

@vars = {:1 => { :name =>
“john”, :location=>“USA”, :comment=>“hello”}, :2=>{ :name =>
“frank”, :location=>“CA”, :comment=>“hi”} }

I tried this:

  @vars = Hash.new { Hash.new }
  Mymodel.all.each do |a|
        @vars["#{a.grouping_id}"] = { :"#{a.title}" =>

a.description }
end

But that only stores the last variable in each grouping ID

h = {}
model.each do |r|
h[r.grouping_id] ||= {}
h[r.grouping_id][:name] = r.name
h[r.grouping_id][:description] = r.description
end

Ahh beautiful… part of your code didn’t work with the || = but I did
this:

  @vars = {}

  Model.all.each do |a|
      if @vars[a.grouping_id] == nil
        @vars[a.grouping_id] = {}
      end
      @vars[a.grouping_id][:"#{a.title}"] = a.description
  end

Brent wrote:

OK I give up, how do I do this…

I have a DB that stores dynamic variables with I group into
group_id’s. For instance here are a couple examples of db rows:

title=“name”, description = “john”, grouping_id = “1”
title=“location”, description = “USA”, grouping_id = “1”
title=“comment”, description = “hello”, grouping_id = “1”

title=“name”, description = “frank”, grouping_id = “2”
title=“location”, description = “CA”, grouping_id = “2”
title=“comment”, description = “hi”, grouping_id = “2”

Sure I could create a DB with these columns, but for various reasons
I’m doing it this way.

And those various reasons are…? In general, it’s best to use a
database for your data store.

SO, how do I store all this information in a hash? I want end up
looking something like this:

@vars = {:1 => { :name =>
“john”, :location=>“USA”, :comment=>“hello”}, :2=>{ :name =>
“frank”, :location=>“CA”, :comment=>“hi”} }

I tried this:

  @vars = Hash.new { Hash.new }
  Mymodel.all.each do |a|
        @vars["#{a.grouping_id}"] = { :"#{a.title}" =>

a.description }
end

But that only stores the last variable in each grouping ID

You probably want an array of hashes, not a hash of hashes.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs