if / elsif / else का इस्तेमाल
if, elsif, और else एक program को paths के बीच choose करने देते हैं, 'अगर ठंड हो एक coat पहनो, नहीं तो अगर बारिश हो एक umbrella लो, नहीं तो एक t-shirt पहनो' की तरह। Ruby उस पहले block को चलाता है जिसका question true हो।
In this page:
Syntax
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
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
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. #}
आम गलतियां
elsifकी बजायelse ifलिखना, जिसे एक extraendचाहिए।- condition में
==की बजाय=इस्तेमाल करना, जो assign करता है। endभूल जाना, इसलिए बाकी fileifके हिस्से की तरह पढ़ी जाती है और एक syntax error appear होता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: