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

Blocks क्या हैं

एक block code का एक chunk है जो आप सही moment पर चलाने के लिए एक method को देते हैं, एक friend को पढ़ने के लिए एक note देने की तरह। यह braces या do और end में method call के ठीक बाद बैठता है।

In this page:

  1. Blocks
Syntax
ruby
collection.method_name { |item| expression }

collection.method_name do |item|
  # body
end

Blocks

लगभग कोई भी Ruby method call एक attached block accept कर सकता है, { ... } या do ... end से लिखा गया, जिसे method yield इस्तेमाल करते हुए zero या ज़्यादा बार चला सकता है।

Blocks वह तरीका हैं जिससे each और map जैसे iteration methods प्रति element चलाने के लिए logic receive करते हैं। एक Proc या Lambda के उलट, एक block खुद एक object नहीं है -- यह सीधे एक single method call से tied syntax है।

Note: short, single-line blocks के लिए { } और लंबे, multi-line blocks के लिए do...end इस्तेमाल करें -- यह community style convention है।

उदाहरण: Blocks

markup
[1, 2, 3].each { |n| puts "Value: #{n}" }

[1, 2, 3].each do |n|
  doubled = n * 2
  puts "Doubled: #{doubled}"
end
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. puts [1, 2, 3].each { ... } लिखना जहाँ braces [1, 2, 3].each से bind होते हैं, लेकिन do ... end के साथ block puts से bind होता है।
  2. यह उम्मीद करना कि block के अंदर defined variables इसके बाद exist करेंगे, जब block-local variables गायब हो जाते हैं।
  3. multi-line blocks के लिए { } और one-liners के लिए do...end इस्तेमाल करना, जब convention दूसरी तरफ है।
🔒

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.