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

if / elsif / else का इस्तेमाल

if, elsif, और else एक program को paths के बीच choose करने देते हैं, 'अगर ठंड हो एक coat पहनो, नहीं तो अगर बारिश हो एक umbrella लो, नहीं तो एक t-shirt पहनो' की तरह। Ruby उस पहले block को चलाता है जिसका question true हो।

In this page:

  1. if / elsif / else
Syntax
ruby
if condition
  # body
elsif other_condition
  # body
else
  # body
end

if / elsif / else

एक if statement सिर्फ तभी इसका block चलाता है जब condition truthy हो, elsif additional conditions chain करता है, और else बाकी सब handle करता है, end से खत्म होते हुए।

Ruby एक trailing modifier form भी support करता है, puts "hi" if condition, simple single-line conditionals के लिए। कई languages के उलट, Ruby में if खुद एक expression है और एक value return करता है।

Note: क्योंकि if एक expression है, आप result = if condition then a else b end लिखकर सीधे इसकी value assign कर सकते हैं।

उदाहरण: if / elsif / else

markup
score = 85

if score >= 90
  puts "Grade: A"
elsif score >= 70
  puts "Grade: B"
else
  puts "Grade: C"
end

puts "High score!" if score > 80
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. elsif की बजाय else if लिखना, जिसे एक extra end चाहिए।
  2. condition में == की बजाय = इस्तेमाल करना, जो assign करता है।
  3. end भूल जाना, इसलिए बाकी file if के हिस्से की तरह पढ़ी जाती है और एक syntax error appear होता है।
🔒

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.