Block के Basics (रिव्यू)
यह review blocks फिर से देखता है: code के छोटे pieces जो एक method को बाद में चलाने के लिए pass किए जाते हैं। यह अपनी request के साथ instructions का एक छोटा set handover करने जैसा है।
In this page:
Syntax
method_name { |param| expression }
method_name do |param|
# body
end
Block Basics (Review)
एक block { } या do...end से एक method call से attached code है, और यह खुद एक object नहीं है -- यह सिर्फ उस specific call के हिस्से की तरह exist करता है, yield के जरिए invoked।
यह tutorial specifically blocks को फिर से देखता है इन्हें Proc और Lambda से contrast करने के लिए, जो similar logic को एक reusable, storable object में बदलते हैं। एक दी गई situation के लिए सही tool चुनने के लिए यह distinction समझना key है।
Note:
एक bare block अपने आप एक variable में store या pass around नहीं हो सकता -- इसके लिए, आपको एक Proc या Lambda चाहिए।
उदाहरण: Block Basics (Review)
def run_twice
yield
yield
end
run_twice { puts "Running from a block" }
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. #}
आम गलतियां
x = { puts 1 }जैसे एक variable में एक block store करने की कोशिश करना, जो valid नहीं है, क्योंकि एक block एक object नहीं है।- एक block को एक hash से confuse करना, क्योंकि दोनों braces इस्तेमाल करते हैं।
- एक method को एक block pass करना जो इसे इस्तेमाल नहीं करता, इसलिए यह silently ignore हो जाता है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: