Arguments के साथ yield (रिव्यू)
yield block को values दे सकता है, जो इन्हें inputs की तरह इस्तेमाल करता है, एक helper को एक ingredient pass करने की तरह। यह review दिखाता है कि method और block कैसे बात करते हैं।
In this page:
Syntax
def method_name
yield value1, value2
end
method_name { |a, b| expression }
Arguments के साथ yield (Review)
एक block yield value से बिल्कुल एक method call की तरह arguments receive कर सकता है, method को block की logic में data feed करने देते हुए। यही exactly वह तरीका है जिससे each जैसे methods current element को आपके block में pass करते हैं।
एक साथ कई values yield हो सकती हैं, कई block parameters से match करते हुए।
Note:
yield हुई values की संख्या exactly block के parameter count से match होने की ज़रूरत नहीं -- extra block parameters बस nil बन जाते हैं।
उदाहरण: yield with Arguments (Review)
def each_pair
yield(1, "one")
yield(2, "two")
end
each_pair { |num, word| puts "#{num}: #{word}" }
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. #}
आम गलतियां
- दो values yield करना लेकिन block एक लेता है,
|num|, इसलिए यह सिर्फ पहली receive करता है। - block की उम्मीद से अलग order में values yield करना, इसलिए
numऔरwordswap हो जाते हैं। - यह उम्मीद करना कि block में बहुत सारे parameters होने पर एक error आएगी, जब extras
nilहैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: