Comparable क्या है
Comparable एक class को इसके objects compare करना सिखाता है, इसे free में bigger और smaller checks देते हुए। यह बच्चों को height से line up करना दिखाने जैसा है।
In this page:
Syntax
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
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))
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
<=>define किए बिनाComparableinclude करना, इसलिए<और>errors raise करते हैं।<=>सेtrueयाfalsereturn करना, जब इसे-1,0,1(याnil) return करना ज़रूरी है।<=>में दूसरी type के एक object से compare करना, जोother.amountmissing होने पर एक error raise करता है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: