Why my program won’t return a sum in a nested hash?

问题内容:

I am supposed to create a multiple choice test which will return the user’s answer and a grade.

I am having problems when calculating the answers

I have this nested hash in a .txt file. I have used YAML to create and run the test.

---
    1+1?:
      '1': 0
      '2': 1
      '3': 0
    2*2?:
      '2': 0
      '4': 1

And I need the code to calculate a final grade.

The problem is that it calculates all the values in the second hash.

Even if the user answered for example “1+1 = 1”, he will still get one point.

def read_test_from_file
  require 'yaml'
  puts Dir.glob("*.txt")
  puts "Insert subject"

  name_check = gets.chomp

  return YAML::load_file("#{name_check}.txt")
end

def take_test

  puts
  test_to_take = read_test_from_file()
  diff_hash    = Hash.new()

  test_to_take.each do |question, diff_hash|
    puts question

    diff_hash.each do |key, value|
      puts "#{key}"
    end

    diff_hash.each do |key, value|
    end

    solution = gets.chomp
    puts
    if diff_hash.has_key? (solution)
      puts diff_hash [solution]

      puts
    end

    test_to_take[question] = diff_hash
    diff_hash["Answer"]    = solution
    total_score += diff_hash[solution] #this is inside the loop as you said
  end
 total_score = 0 # and this one outside the loop
 puts total_score
end

puts take_test

Can someone help me? Please.

问题评论:

    
I don’t see how user would get any points here. You’re not using the points in any way (except printing).
    
Also don’t tag non-rails questions with [ruby-on-rails]
    
Well, I’m not so sure how to use the points. I’m new in ruby and all I did so far is from what I have found on the internet. So there are lots of things which I don’t know…
– Alin Chiver
21 hours ago
    
And as for the inject(&:+) question: you know what it does, right?
    
It adds all the elements together. For example if I’d have integers it’ll sum them, and if is string it will just combine it. Eg. if the hash will have “1”, “0” inject will return 10.
– Alin Chiver
21 hours ago

原文地址:

https://stackoverflow.com/questions/47741896/why-my-program-wont-return-a-sum-in-a-nested-hash

Tags:

添加评论

友情链接:蝴蝶教程