I'm new to Ruby
, and I'm trying to implement a comparison between Grades
, was shown in the example
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]
So, I'm getting:
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>'
I just want to implement Comparison
between objects in Ruby
From Ruby Doc module Comparable:
Comparable uses <=> to implement the conventional comparison operators (<, <=, ==, >=, and >) and the method between?.
When you want to implement such thing, only implement <=>
. The rest should automatically follow. If you define <
, for example, you will mess up the class.
You can do something like this:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With