这是我下面代码的一部分,无论如何,这是唯一不起作用的东西。我很困惑。
def change_numbers_to_grade_points
@course_grades.each do |grade|
case
when grade < 100 && grade > 93.99
grade == 4.0
when grade < 93.99 && grade > 89.99
grade == 3.7
when grade < 88.99 && grade > 86.99
grade == 3.3
when grade < 86.99 && grade > 82.99
grade == 3.0
when grade < 82.99 && grade > 79.99
grade == 2.7
when grade < 79.99 && grade > 76.99
grade == 2.3
when grade < 76.99 && grade > 72.99
grade == 2.0
when grade < 72.99 && grade > 69.99
grade == 1.7
when grade < 69.99 && grade > 66.99
grade == 1.3
when grade < 66.99 && grade > 59.99
grade == 1.0
when grade < 59.99 && grade > 0
grade == 0.0
else
puts "Something went wrong with conversion!"
puts
end
end
end
答案 0 :(得分:2)
==
是平等的。您想使用=
进行分配。
例如:
when grade < 100 && grade > 93.99
grade = 4.0
然而,这也不是问题,因为您没有修改数组中的任何元素,而是使用.each
循环进行迭代
考虑类似
的内容@course_grades.size.times do |i|
grade = @course_grades[i]
if # something
@course_grades[i] = #some new value
end
end
答案 1 :(得分:0)
正如其他用户建议的那样,您应该使用map!
,因为您希望使用case
的结果替换原始数组的内容。顺便说一下,您可以使用lambdas
而不是Ranges
。如下:
# Since your method is changing the contents of
# an instance variable, the convention is that
# your method ends with a bang (!)
def change_numbers_to_grade_points!
@course_grades.map! do |grade|
case grade
when 93.99..100
4.0
when 89.99..93.99
3.7
when 86.99..88.99
3.3
when 82.99..86.99
3.0
#...
#An error is raised if something is wrong because of map!
else
raise "Something went wrong"
end
end