Search code examples
rubyhashruby-on-rails-5

How to dynamically build a Hash dataset in Rails?


I'm working to build a chartjs data object that contains a dynamic number of datasets. In my Ruby on Rails 5 controller, I'm trying the following:

chartJsObject = []

chartJsObject << {
  label: "Label Stuff",
  datasets: []
}

i = 0
num = 5

while i < num  do
  chartJsObject.datasets << [rand(10), rand(10)]
   i+=1
end

This is resulting in the following error:

undefined method `datasets' for [{:label=>"Label Stuff", :datasets=>[]}]:Array

Any ideas what I'm doing wrong here to be able to loop through and populate chartJsObject.datasets?


Solution

  • In the first line you define chartJsObject as an array:

    chartJsObject = []
    

    then in the second, you push a hash object in it:

    chartJsObject << {
      label: "Label Stuff",
      datasets: []
    } #=> [{:label=>"Label Stuff", :datasets=>[]}]
    

    Now, what you have is an array of hash objects. In order to insert the data in datasets you just need access to the hash object, probably like so:

    i = 0
    num = 5
    
    while i < num  do
      chartJsObject[i][:datasets] << [rand(10), rand(10)] if chartJsObject[i]
      i+=1
    end