← Back to Ruby Course | Chapter 8: Blocks, Procs & Lambdas | Lesson 1 of 6

Block के Basics (रिव्यू)

यह review blocks फिर से देखता है: code के छोटे pieces जो एक method को बाद में चलाने के लिए pass किए जाते हैं। यह अपनी request के साथ instructions का एक छोटा set handover करने जैसा है।

In this page:

  1. Block Basics (Review)
Syntax
ruby
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)

markup
def run_twice
  yield
  yield
end

run_twice { puts "Running from a block" }
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. x = { puts 1 } जैसे एक variable में एक block store करने की कोशिश करना, जो valid नहीं है, क्योंकि एक block एक object नहीं है।
  2. एक block को एक hash से confuse करना, क्योंकि दोनों braces इस्तेमाल करते हैं।
  3. एक method को एक block pass करना जो इसे इस्तेमाल नहीं करता, इसलिए यह silently ignore हो जाता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.