arrays - Nil errors in creating a hash in Ruby on Rails -
i'm running several syntax , nil issues when trying create hash idea_benefit_count
.
@idea = @domain.ideas @idea_evaluations = array.new() @idea.each |idea| @idea_evaluations << idea.evaluations end @idea_benefit = [] if !@idea_evaluations.nil? @idea_evaluations.each |eval| @idea_benefit << eval.benefit end @idea_benefit_count = hash.new(0) @idea_benefit.flatten.each { |idea_benefit| @idea_benefit_count[idea_benefit] += 1 } end
an idea has_many domains
, @idea
should of ideas has given @domain
.
@idea_evaluations
array of evaluations belong_to
specific idea
.
@idea_benefit
array of arrays holds of each evaluation's benefit
entries. example output: [["happier_customers"], ["happier_employees"], ["happier_employees", "decreased_costs"], ["happier_employees"]]
idea_benefit_count
reads idea_benefit
, counts how many of each type of benefit idea has. output of idea_benefit_count
based on above idea_benefit
array {"happier_customers"=>1, "decreased_costs"=>1, "happier_employees"=>3}
(hopefully context covers everything)
my current error undefined method 'benefit'
on line @idea_benefit << eval.benefit
. benefit
attribute of evaluation
, should output ["happier_customers"]
.
i realize code bit of mess, suggestions super helpful on getting entire thing working. big problem checking see if there evaluations
belonging idea
, because if comes nil
throws error. tried fix if !@idea_evaluations.nil?
check, haven't been able test yet because of undefined method 'benefit'
error.
edit
@idea_evaluations = array.new() @idea.each |idea| @idea_evaluations << idea.evaluations end @idea_evaluations.flatten! @idea_benefit = [] unless !@idea_evaluations.nil? @idea_evaluations.each |eval| @idea_benefit << eval.benefit end @idea_benefit_count = hash.new(0) @idea_benefit.flatten.each { |idea_benefit| @idea_benefit_count[idea_benefit] += 1 } end
the problem see if understand trying way dumping idea.evaluations @idea_evaluations.
@idea_evaluations going array of arrays of evaluations not array of evaluations think.
e.g. [[eval1,eval2],[eval3,eval4,eval5]]
instead of [eval1, eval2, eval3, eval4, eval5]
when try access benefit, attempts benefit method array not exist.
try altering
@idea.each |idea| @idea_evaluations << idea.evaluations end
to be
@idea.each |idea| @idea_evaluations << idea.evaluations end @idea_evaluations.flatten!
also in ruby don't do
if !condition
you
unless condition
Comments
Post a Comment