← Back to Ruby Course | Chapter 6: Control Flow | Lesson 3 of 7

case / when का इस्तेमाल

case और when एक value को options की एक list के against compare करते हैं, आपका button match करने वाली एक vending machine की तरह। Ruby पहले fit होने वाले option का block चलाता है।

In this page:

  1. case / when
Syntax
ruby
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

markup
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
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. when के अंदर = या == के साथ case इस्तेमाल करना, जैसे when value == 1, जब यह automatically === से value compare करता है।
  2. यह उम्मीद करना कि एक when C की तरह अगले में fall through करेगा, जब सिर्फ पहला match चलता है।
  3. else भूल जाना, इसलिए एक unmatched value silently nil देती है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.