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

yield क्या है

yield वह तरीका है जिससे एक method इसे दिया गया block चलाता है, एक chef की तरह जो आपकी दी special step चलाने के लिए pause करता है। Method decide करता है कि block को कब turn मिलती है।

In this page:

  1. yield
Syntax
ruby
def method_name
  yield
end

method_name { # block body }

yield

एक method के अंदर, yield इसे pass किए गए block को invoke करता है, optionally block में values को arguments की तरह pass करते हुए।

block_given? yield करने से पहले check करता है कि actually एक block दिया गया या नहीं, अगर caller एक pass करना भूल जाए तो एक error avoid करते हुए। यही mechanism है जो आपको अपने खुद के methods लिखने देता है जो each या map जैसे behave करते हैं।

Note: जब तक एक block strictly required न हो हमेशा yield को if block_given? से guard करें, कोई न दिए जाने पर एक LocalJumpError से बचने के लिए।

उदाहरण: yield

markup
def repeat_twice
  yield
  yield
end

repeat_twice { puts "Hello!" }

def with_value
  if block_given?
    yield(42)
  else
    puts "No block given"
  end
end

with_value { |n| puts "Got: #{n}" }
with_value
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. कोई block न दिए जाने पर yield call करना, जो LocalJumpError raise करता है; block_given? से guard करें।
  2. yield को ऐसे arguments pass करना जो block accept नहीं करता, और एक error की उम्मीद करना, जब extra values ignore हो जाते हैं।
  3. एक method के अंदर yield लिखना और call पर block भूल जाना, इसलिए कुछ नहीं होता।
चैप्टर सारांश
  • Methods parameters, default parameters, और return values के साथ defined होते हैं।
  • Splat operator (*args) और keyword arguments (**kwargs) flexible inputs accept करते हैं।
  • Blocks और yield एक method को इसे pass किया code चलाने देते हैं।
🔒

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.