我是 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>'
我只想在 Ruby 中实现对象之间的比较
最佳答案
来自 Ruby Doc module Comparable :
Comparable uses <=> to implement the conventional comparison operators (<, <=, ==, >=, and >) and the method between?.
当你想实现这样的东西时,只实现<=>
.其余的应该自动跟随。如果定义 <
,例如,你会把类(class)搞得一团糟。
你可以这样做:
class Grade
include Comparable
attr_reader :index
@@grades = %w[F D- D D+ C- C C+ B- B B+ A- A+]
def initialize (grade = nil); @index = @@grades.index(grade).to_i end
def <=> (other); @index <=> other.index end
end
a_plus = Grade.new("A+")
a = Grade.new("A")
a_plus > a
# => true
[a_plus, a].sort
# => `[a, a_plus]` will be given in this order
关于ruby - 实现比较运算符 - Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13973675/