Blocks क्या हैं
एक block code का एक chunk है जो आप सही moment पर चलाने के लिए एक method को देते हैं, एक friend को पढ़ने के लिए एक note देने की तरह। यह braces या do और end में method call के ठीक बाद बैठता है।
In this page:
Syntax
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
[1, 2, 3].each { |n| puts "Value: #{n}" }
[1, 2, 3].each do |n|
doubled = n * 2
puts "Doubled: #{doubled}"
end
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. #}
आम गलतियां
puts [1, 2, 3].each { ... }लिखना जहाँ braces[1, 2, 3].eachसे bind होते हैं, लेकिनdo ... endके साथ blockputsसे bind होता है।- यह उम्मीद करना कि block के अंदर defined variables इसके बाद exist करेंगे, जब block-local variables गायब हो जाते हैं।
- multi-line blocks के लिए
{ }और one-liners के लिएdo...endइस्तेमाल करना, जब convention दूसरी तरफ है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: