我是新手Ruby
,我正在尝试在 之间进行比较Grades
,如示例中所示
include Comparable
class Grade
attr_accessor :grades, :grade
def initialize( grade = "" )
self.grades = { :nil => -1, :"F" => 0, :"D-" => 1, :"D" => 2, :"D+" => 3,
:"C-" => 4, :"C" => 5, :"C+" => 6, :"B-" => 7, :"B" => 8,
:"B+" => 9, :"A-" => 10, "A+" => 11 }
if self.grades[ grade ]
self.grade = grade
else
self.grade = nil
end
end
def <=>( other )
if self.grades[ self.grade ] < self.grades[ other.grade ]
return -1
elsif self.grades[ self.grade ] == self.grades[ other.grade ]
return 0
else
return 1
end
end
end
a_plus = Grade.new("A+")
a = Grade.new("A")
[a_plus, a].sort # should return [a, a_plus]
所以,我得到:
grade.rb:31:in `<': comparison of Fixnum with nil failed (ArgumentError)
from grade.rb:31:in `<=>'
from grade.rb:43:in `sort'
from grade.rb:43:in `<main>'
我只想Comparison
在 Ruby 中的对象之间实现