case / when का इस्तेमाल
case और when एक value को options की एक list के against compare करते हैं, आपका button match करने वाली एक vending machine की तरह। Ruby पहले fit होने वाले option का block चलाता है।
In this page:
Syntax
case value
when pattern1
# body
when pattern2, pattern3
# body
else
# default
end
case / when
एक case statement एक value को when patterns की एक series के against compare करता है, पहले match के लिए block चलाते हुए -- दूसरी languages में switch statements का Ruby equivalent, लेकिन ज़्यादा powerful matching के साथ।
when internally === operator इस्तेमाल करता है, जो patterns को class, range, या regex से match करने देता है, सिर्फ equality नहीं। else किसी पहले वाले when से match न हुई किसी भी चीज़ को handle करता है।
Note:
when एक Class, एक Range, या एक Regexp match कर सकता है, सिर्फ एक exact value नहीं -- case x; when Integer then ... काम करता है।उदाहरण: case / when
value = 42
case value
when 1..10
puts "Small number"
when 11..100
puts "Medium number"
else
puts "Large number"
end
case value
when String
puts "It's a string"
when Integer
puts "It's an integer"
end
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. #}
आम गलतियां
whenके अंदर=या==के साथcaseइस्तेमाल करना, जैसेwhen value == 1, जब यह automatically===से value compare करता है।- यह उम्मीद करना कि एक
whenC की तरह अगले में fall through करेगा, जब सिर्फ पहला match चलता है। elseभूल जाना, इसलिए एक unmatched value silentlynilदेती है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: