Newbies को समानता के तरीकों से परेशानी होगी :
- a == b : जाँच करता है कि क्या a और b बराबर हैं। यह सबसे उपयोगी है।
- a.eql? b : यह भी जाँचता है कि क्या a और b बराबर हैं, लेकिन यह कभी-कभी अधिक सख्त होता है (यह जाँच सकता है कि a और b का एक ही प्रकार है, उदाहरण के लिए)। यह मुख्य रूप से हैश में उपयोग किया जाता है।
- a.equal? b : चेक करता है कि क्या a और b एक ही ऑब्जेक्ट (आइडेंटिटी चेक) हैं।
- a === b : केस स्टेटमेंट्स में उपयोग किया जाता है (मैंने इसे " माचिस बी " के रूप में पढ़ा )।
इन उदाहरणों को पहले 3 तरीकों को स्पष्ट करना चाहिए:
a = b = "joe"
a==b # true
a.eql? b # true
a.equal? b # true (a.object_id == b.object_id)
a = "joe"
b = "joe"
a==b # true
a.eql? b # true
a.equal? b # false (a.object_id != b.object_id)
a = 1
b = 1.0
a==b # true
a.eql? b # false (a.class != b.class)
a.equal? b # false
ध्यान दें कि == , eql? और बराबर? हमेशा सममित होना चाहिए: यदि ए = बी तो बी == ए।
यह भी ध्यान दें कि == और eql? क्या दोनों को क्लास ऑब्जेक्ट के रूप में लागू किया जाता है? , तो यदि आप एक नया वर्ग बनाते हैं और चाहते हैं == और eql? सादे पहचान के अलावा कुछ और मतलब है, तो आपको उन दोनों को ओवरराइड करने की आवश्यकता है। उदाहरण के लिए:
class Person
attr_reader name
def == (rhs)
rhs.name == self.name # compare person by their name
end
def eql? (rhs)
self == rhs
end
# never override the equal? method!
end
=== विधि अलग ढंग से व्यवहार करता है। सबसे पहले यह सममित नहीं है (ए = बी का मतलब यह नहीं है कि बी === ए)। जैसा कि मैंने कहा, आप एक === b को "एक माचिस b" के रूप में पढ़ सकते हैं। कुछ उदाहरण निम्नलिखित हैं:
# === is usually simply an alias for ==
"joe" === "joe" # true
"joe" === "bob" # false
# but ranges match any value they include
(1..10) === 5 # true
(1..10) === 19 # false
(1..10) === (1..10) # false (the range does not include itself)
# arrays just match equal arrays, but they do not match included values!
[1,2,3] === [1,2,3] # true
[1,2,3] === 2 # false
# classes match their instances and instances of derived classes
String === "joe" # true
String === 1.5 # false (1.5 is not a String)
String === String # false (the String class is not itself a String)
मामले कथन पर आधारित है === विधि:
case a
when "joe": puts "1"
when 1.0 : puts "2"
when (1..10), (15..20): puts "3"
else puts "4"
end
इसके बराबर है:
if "joe" === a
puts "1"
elsif 1.0 === a
puts "2"
elsif (1..10) === a || (15..20) === a
puts "3"
else
puts "4"
end
यदि आप एक नए वर्ग को परिभाषित करते हैं, जिसके उदाहरण किसी प्रकार के कंटेनर या रेंज का प्रतिनिधित्व करते हैं (यदि इसमें कुछ शामिल है? या एक मैच? विधि), तो आपको इस तरह से === विधि को ओवरराइड करना उपयोगी हो सकता है :
class Subnet
[...]
def include? (ip_address_or_subnet)
[...]
end
def === (rhs)
self.include? rhs
end
end
case destination_ip
when white_listed_subnet: puts "the ip belongs to the white-listed subnet"
when black_listed_subnet: puts "the ip belongs to the black-listed subnet"
[...]
end