← Back to Ruby Course | Chapter 7: Methods | Lesson 1 of 7

Method के Basics

एक method एक named recipe है जो आप एक बार लिखते हैं और जब चाहें इस्तेमाल करते हैं। Ruby में आप def से शुरू करते हैं और end से खत्म करते हैं।

In this page:

  1. Method Basics
Syntax
ruby
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

markup
def greet
  puts "Hello from a method!"
end

greet
greet()
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. इसका def execute होने से पहले एक method call करना, जो एक script में NameError raise करता है क्योंकि methods file चलते हुए define होते हैं।
  2. body के बाद end भूल जाना।
  3. एक local variable से match करने वाले नाम के साथ def greet define करना, इसलिए greet variable पढ़ता है, जब parentheses के साथ greet() method call करता है।
🔒

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.