for और each
for एक बार में एक item से गुज़रता है, लेकिन Ruby fans each prefer करते हैं, जो same काम एक ज़्यादा Ruby style में करता है। यह desks की एक row से चलने के दो तरीकों जैसा है।
In this page:
Syntax
for item in collection
# body
end
collection.each do |item|
# body
end
for और each
Ruby में एक for item in collection loop है, लेकिन idiomatic Ruby लगभग हमेशा इसकी बजाय collection.each { |item| ... } prefer करता है, क्योंकि each अपना loop variable surrounding scope में leak नहीं करता जैसे for करता है।
each खुद collection पर एक method call है, एक separate loop keyword से बेहतर Ruby की block-and-method-driven style में fit होते हुए। आप real Ruby code में for rarely देखेंगे।
Warning:
for loop खत्म होने के बाद इसका loop variable enclosing scope में leak करता है, जबकि each का block variable properly scoped रहता है -- each prefer होने की एक और वजह।
उदाहरण: for and each
for i in 1..3
puts "for loop: #{i}"
end
(1..3).each do |i|
puts "each loop: #{i}"
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. #}
आम गलतियां
- यह उम्मीद करना कि एक
forloop का अपना scope होगा, जब loop variableiloop के बाद available रहता है। - habit से एक बड़ी या बदलती collection के साथ
forइस्तेमाल करना, जबeachidiomatic choice है। - बिना parentheses के
1..3.eachइस्तेमाल करना, range की बजाय3परeachcall करते हुए।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: