ruby Ruby:宇宙飞船

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Ruby:宇宙飞船相关的知识,希望对你有一定的参考价值。

# == Description
# the <=> operator returns 1, 0, or -1, depending on the value of the left arugment relative to the right
# This operator is good to use when you want to define how to compare two like object
# The operator must return -1 for less than, 1 for greater than, and 0 for equal to
class Expense
  
  # Modules
  include Comparable
  
  # Accessors
  attr_accessor :amount

  # ==== Description
  # overwrite the spaceship operator
  # When the method is evaluated, it compares the 
  # amount member of the current object to the
  # amount member of the expense object passed in.
  # It will return 1 for less than, 1 for greater than
  # and 0 for equal to.
  def <=>(expense) # You pass in an expense object

    self.amount <=> expense.amount
  end 
end
expense1 = Expense.new()
expense2 = Expense.new()
expense1.amount = 1 
expense2.amount = 2 
puts expense1 <=> expense2 # returns -1
expense1.amount = 1 
expense2.amount = 1 
puts expense1 <=> expense2 # returns 0
expense1.amount = 2 
expense2.amount = 1 
puts expense1 <=> expense2 # returns 1

以上是关于ruby Ruby:宇宙飞船的主要内容,如果未能解决你的问题,请参考以下文章

宇宙最正红色——MAC Ruby Woo

Javascript中的组合比较/“宇宙飞船”运算符(<=>)?

ruby [Ruby Cheat] Cheatsheet #ruby

Ruby运算符

Ruby 25 岁了!Ruby 之父说 Ruby 3 有望 3 倍提速

如何学习ruby?Ruby学习技巧分享