creating dynamic hash with key and value in ruby on rails

arrays, hash, multidimensional-array, ruby, ruby-on-rails

Solution

You are re-assigning `test` with a new hash on each iteration. You should add to it, so instead of

test ={i => s1.power}

you should do:

test[i] = s1.power

This sets the value of key `i` to `s1.power`

If you want to keep an array of all the values for a given key, I would suggest the following (more ruby-ish) solution:

hour_idx = array.find_index { |item| s.duration.start.hour == item.hour }

values = case s.type.to_s
  when 'M'
    s.sgs.map(&:_power)
  when 'L'
    puts "to be done"
  else
    puts "Not  Found"
  end

test = { hour_idx => values }

What I'm doing here is:

- Find the `hour_idx` which is relevant to the current `s` (I assume there is only one such item)

- Create an array of all the relevant values according to `s.type` (if it is `'M'` an array of all the `_power` of `s.sgs`, for `'L'` whatever map you need, and `nil` otherwise)

- Create the target hash using the values set in #1 and #2...

Problem

I am trying to create Hash with dynamic key and respective values. For example like this ``` hash = {1 => 23.67, 1 => 78.44, 3 => 66.33, 12 => 44.2} ``` Something like this in which 1,2,12 are array index. I hope it is understandable. I am trying with the syntax from ROR tutorials. Like this ``` test = Hash.new for i in 0..23 if (s.duration.start.hour == array[i].hour) s.sgs.each do |s1| case s1.type.to_s when 'M' test ={i => s1.power} # here I am trying to create hash like give example in which i is for loop value when 'L' puts "to be done done" else puts "Not Found" end end end end end ``` Updated code ``` test = Hash.new for i in 0..23 if (s.duration.start.hour == array[i].hour) s.sgs.each do |s1| case s.type.to_s when 'M' puts s1.power; test[i] = s1._power when 'L' puts "to be done" else puts "Not Found" end end end end ``` Results on traversing ``` for t in 0..array.size puts test[t] end ``` Results : ``` t = 68.6 # which is last value ``` and expected ``` t = 33.4 t = 45.6 etc ``` Sample logs ``` after assign {23=>#<BigDecimal:7f3a1e9a6870,'0.3E2',9(18)>} before assign {23=>#<BigDecimal:7f3a1e9a6870,'0.2E2',9(18)>} after assign {23=>#<BigDecimal:7f3a1e9ce550,'-0.57E2',9(18)>} before assign {23=>#<BigDecimal:7f3a1e9ce550,'-0.57E2',9(18)>} ``` if any other optimised solution is there would be good thanks

Original source