Method के Basics
एक method एक named recipe है जो आप एक बार लिखते हैं और जब चाहें इस्तेमाल करते हैं। Ruby में आप def से शुरू करते हैं और end से खत्म करते हैं।
In this page:
Syntax
def method_name
# body
end
method_name
Method Basics
एक Ruby method def method_name ... end से define होता है, और context के हिसाब से इसके नाम से, parentheses के साथ या बिना, call होता है।
Method names conventionally snake_case इस्तेमाल करते हैं, और convention से, ? से खत्म होने वाला एक method एक boolean return करता है जबकि ! से खत्म होने वाला एक mutating या "dangerous" operation perform करता है। हर method एक value return करता है, या तो explicitly return से या implicitly अपने last expression की value की तरह।
Note:
Ruby में method arguments के चारों ओर parentheses optional हैं, लेकिन idiomatic style आमतौर पर arguments लेने वाले methods के लिए इन्हें include करती है।
उदाहरण: Method Basics
def greet
puts "Hello from a method!"
end
greet
greet()
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. #}
आम गलतियां
- इसका
defexecute होने से पहले एक method call करना, जो एक script मेंNameErrorraise करता है क्योंकि methods file चलते हुए define होते हैं। - body के बाद
endभूल जाना। - एक local variable से match करने वाले नाम के साथ
def greetdefine करना, इसलिएgreetvariable पढ़ता है, जब parentheses के साथgreet()method call करता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: