← Back to Ruby Course | Chapter 6: Control Flow | Lesson 5 of 7

for और each

for एक बार में एक item से गुज़रता है, लेकिन Ruby fans each prefer करते हैं, जो same काम एक ज़्यादा Ruby style में करता है। यह desks की एक row से चलने के दो तरीकों जैसा है।

In this page:

  1. for और each
Syntax
ruby
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

markup
for i in 1..3
  puts "for loop: #{i}"
end

(1..3).each do |i|
  puts "each loop: #{i}"
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. यह उम्मीद करना कि एक for loop का अपना scope होगा, जब loop variable i loop के बाद available रहता है।
  2. habit से एक बड़ी या बदलती collection के साथ for इस्तेमाल करना, जब each idiomatic choice है।
  3. बिना parentheses के 1..3.each इस्तेमाल करना, range की बजाय 3 पर each call करते हुए।
🔒

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.