← Back to Ruby Course | Chapter 10: Modules & Mixins | Lesson 3 of 6

Comparable क्या है

Comparable एक class को इसके objects compare करना सिखाता है, इसे free में bigger और smaller checks देते हुए। यह बच्चों को height से line up करना दिखाने जैसा है।

In this page:

  1. Comparable
Syntax
ruby
class ClassName
  include Comparable

  def <=>(other)
    attribute <=> other.attribute
  end
end

Comparable

Comparable module mix करना एक class को automatically <, >, <=, >=, ==, और .between? देता है, जब तक class एक single <=> ("spaceship") method define करे जो -1, 0, या 1 return करे।

यह एक अच्छा example है कि एक module आपके दिए code की थोड़ी मात्रा से कितनी functionality add कर सकता है। यह कुछ दूसरी languages में IComparable जो role play करता है उसे mirror करता है।

Note: सिर्फ <=> implement करना और Comparable include करना आपको छह comparison operators plus .between? free में देता है।

उदाहरण: Comparable

markup
class Money
  include Comparable
  attr_reader :amount

  def initialize(amount)
    @amount = amount
  end

  def <=>(other)
    amount <=> other.amount
  end
end

a = Money.new(10)
b = Money.new(20)

puts a < b
puts a.between?(Money.new(5), Money.new(15))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. <=> define किए बिना Comparable include करना, इसलिए < और > errors raise करते हैं।
  2. <=> से true या false return करना, जब इसे -1, 0, 1 (या nil) return करना ज़रूरी है।
  3. <=> में दूसरी type के एक object से compare करना, जो other.amount missing होने पर एक error raise करता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.