Để triển khai module Comparable, bạn phải định nghĩa toán tử nào?
Để triển khai module Comparable, bạn phải định nghĩa toán tử nào?
Để dùng Comparable, bạn chỉ cần định nghĩa toán tử <=> (spaceship) và include Comparable.
class Version
include Comparable
attr_reader :major, :minor
def initialize(major, minor) = (@major, @minor = major, minor)
def <=>(other)
return nil unless other.is_a?(Version)
[major, minor] <=> [other.major, other.minor]
end
end
Version.new(1, 2) < Version.new(1, 10) # => true
Version.new(2, 0).between?(Version.new(1, 0), Version.new(3, 0)) # => true
[Version.new(2,0), Version.new(1,5)].min # dùng <=>
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.