Ruby String无法强制进入Fixnum

时间:2013-10-21 06:02:38

标签: ruby

我正在尝试创建一个从学生记录中计算GPA的程序。输入学生的姓氏和名字后,我收到了这些错误:

Please provide the last name of the desired student:  
Cirello  
Please provide the first name of the desired student:  
Brian  
proj3.rb:55:in `+': String can't be coerced into Fixnum (TypeError)  
        from proj3.rb:55:in `block in <main>'  
        from proj3.rb:53:in `each'  
        from proj3.rb:53:in `<main>' 

请帮我解决这个问题。这是我的代码:

stud_id = []
last_name = []
first_name = []
course_number = []
course_name = []
prof_name = []
credit_hours = []
grade = []

grade_values = {                          
    "A" => 4,                     
    "B" => 3,
    "C" => 2,
    "D" => 1,
    "F" => 0 }

fin = File.open("student-records.txt", "r")

while line = fin.gets
    fields = line.chomp.split(',')
    stud_id << fields[0]
    last_name << fields[1]
    first_name << fields[2]
    course_number << fields[3]
    course_name << fields[4]
    prof_name << fields[5]
    credit_hours << fields[6]
    grade << fields[7]
end

fin.close

puts "Please provide the last name of the desired student:"
    desired_last_name = gets.chomp
puts "Please provide the first name of the desired student:"
    desired_first_name = gets.chomp

desired_student_credit_hours = 0
desired_student_grades = 0
desired_student_indexes = [7]
if last_name.include?(desired_last_name) && first_name.include?(desired_first_name)
    last_name.each do |student_last_name, i|
        if student_last_name == desired_last_name
            desired_student_indexes << i
        end
    end
end
desired_student_indexes.each do |desired_student_index|
    desired_student_grades += grade_values[grade[desired_student_index]]
    desired_student_credit_hours += credit_hours[desired_student_index]
end
final_gpa = desired_student_grades / desired_student_credit_hours
puts "This student's final GPA is: #{final_gpa}"

1 个答案:

答案 0 :(得分:1)

请检查将字符串转换为整数的to_i方法。您需要将其附加到grade_values[grade[desired_student_index]]credit_hours[desired_student_index],如下所示:

desired_student_grades += grade_values[grade[desired_student_index]].to_i
desired_student_credit_hours += credit_hours[desired_student_index].to_i