ruby - 实现比较运算符 - Ruby

标签 ruby

我是 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/

相关文章:

ruby-on-rails - Rspec - 测试方法在另一个方法内收到调用

ruby-on-rails - form_for 详细信息未显示在 View :Ruby on Rails 中

javascript - 根据 ruby​​ 逻辑将确认弹出窗口附加到按钮元素

ruby-on-rails - 如何在生产中运行 Rails Web 控制台?

ruby-on-rails - 字符串比较在 Ruby 中不起作用

ruby - ActiveJob::SerializationError - 不支持的参数类型:Time/DateTime

ruby-on-rails - 如何将默认参数传递给 Rails lambda/scopes?

ruby-on-rails - 日志在生产中无法正常工作,作业延迟

ruby - if 语句检查在 ruby​​ 中不起作用

ruby - 查找包含特定文本的表格