1

dI am writing a Model function that is iterating over a hash, whose keys are named the same as model attribute names. I would like to compare the values of the hash key to the value that is contained in the model attribute of the same name. However, when I generate the attribute name, I do not know how to actually refer to the actual model name and its corrresponding attribute. Currently I am doing the following:

 def grade 
   num_correct = 0
   answers = self.class.answers
   answers.each do |question, value|
     db_question = question
     num_correct = num_correct + 1 if db_question.to_i == value
   end


   if num_correct < 22
     return "Beginner"
   elsif num_correct >= 22 and num_correct < 41
     return "Intermediate"
   else
     return "Advanced"
   end 
 end

I would like db_question to actually be the model attribute "db_question", however i am not sure how to make the shift from the simple string which is equivalent to the actual model attribute to the model attribute per se.

Thalatta
  • 4,510
  • 10
  • 48
  • 79
  • 2
    Did you try using `send` method. I think that would do the needful. A link how it works: http://stackoverflow.com/questions/7895253/rails-100-newb-issue-send-method – Deepesh Feb 10 '15 at 01:12
  • (explicit returns are not needed in ruby when placed at the end) – froderik Feb 10 '15 at 04:19

1 Answers1

1

In your case:

value = model.send 'Beginner'.downcase.to_sym

Generically - making a string print itself.....:

'yolo'.send 'to_s'.to_sym

equivalent to

'yolo'.to_s

equivalent to

'yolo'
froderik
  • 4,642
  • 3
  • 33
  • 43