reesaspieces
reesaspieces

Reputation: 1810

How to access hashes whose keys are arrays in Rails?

I am trying to access data that has a structure like this (the status of each user on specific dates). As you can see, the hash keys are all arrays. This data has been retrieved from the DB using group_by.

data = {
  ["active", "Rick"]=>["2019-07-09", "2019-07-10"],
  ["active", "Morty"]=>["2019-07-09", "2019-07-10"],
  ["active", "Summer"]=>["2019-07-09", "2019-07-10"],
  ["inactive", "Rick"]=> ["2019-07-01", "2019-07-02", "2019-07-03"],
  ["inactive", "Summer"]=>["2019-07-15"]
}

I would rather have this data be a nested hash, like below. Is there a way to restructure it?

I know that each item in the hash can be accessed like this: data[["active", "Summer"]]. I tried doing something like data[["active", "*"]] (to get the active status data for all users) but this did not work.

data = {
  "active"=>{
    "Rick"=>["2019-07-09", "2019-07-10"],
    "Morty"=>["2019-07-09", "2019-07-10"],
    "Summer"=>["2019-07-09", "2019-07-10"]
  },
  "inactive"=>{
    "Rick"=>["2019-07-01", "2019-07-02", "2019-07-03"],
    "Summer"=>["2019-07-15"]
  }
}

Upvotes: 0

Views: 63

Answers (2)

Smek
Smek

Reputation: 1208

This should work:

new_data = {}
data.each do |k, v|
  new_data[k.first] ||= []
  new_data[k.first] << { k.last => v}
end

But if you are in control of the db/query, perhaps it is better to retrieve your data from the db in the right format right away if possible.

Upvotes: 2

Parakh Garg
Parakh Garg

Reputation: 119

You can do something like this -

    new_data = { 'active' => [], 'inactive' => [] }
    data.each do |key, value|
      if key.first == 'active'
        new_data['active'] << { key.last => value }
      elsif key.first == 'inactive'
        new_data['inactive'] << { key.last => value }
      end
    end

Upvotes: 1

Related Questions