yield क्या है
yield वह तरीका है जिससे एक method इसे दिया गया block चलाता है, एक chef की तरह जो आपकी दी special step चलाने के लिए pause करता है। Method decide करता है कि block को कब turn मिलती है।
In this page:
Syntax
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
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
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. #}
आम गलतियां
- कोई block न दिए जाने पर
yieldcall करना, जोLocalJumpErrorraise करता है;block_given?से guard करें। yieldको ऐसे arguments pass करना जो block accept नहीं करता, और एक error की उम्मीद करना, जब extra values ignore हो जाते हैं।- एक 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: