RahulOnRails
RahulOnRails

Reputation: 6542

ROR + Count of all JSON value present in one column

In my rails app, I want to add few values present in one column in the form of key-value pair. I am not getting the way to add them.

(byebug) p @timing_params.data_date_wise
{"2"=>"7", "3"=>"8", "4"=>"9", "5"=>"10", "6"=>"11", "9"=>"", "10"=>"", "11"=>""
, "12"=>"", "13"=>"", "16"=>"", "17"=>"", "18"=>"", "19"=>"", "20"=>"", "23"=>""
, "24"=>"", "25"=>"", "26"=>"", "27"=>"", "30"=>"", "31"=>""}

Controller:

total_hour = 0
total_day_count = @timing_params.data_date_wise.count
puts "total_day_count = #{total_day_count}"

for i in 1..total_day_count
  total_hour+= @timing_params.data_date_wise["i"] if @timing_params.data_date_wise["i"].to_i > 0
  puts "date : #{@timing_params.data_date_wise['i']}"
end
puts "TotalHour : #{total_hour}"

Another problem I think is - All details are not in sequence so that only values will be calculated. For example count is 22 then as per the data - 23 to 31 will be missed.

Please suggest something...

Upvotes: 0

Views: 142

Answers (1)

Greg
Greg

Reputation: 76

How about changing your for loop to iterate through the hash like this:

@timing_params.data_date_wise.each do |date,value|
  total_hour += value.to_i if value.to_i > 0
end

Upvotes: 1

Related Questions