2008-09-30 14 views
23

में रूबी में है:क्या "के लिए" रूबी

for i in A do 
    # some code 
end 

में ही है के रूप में:

  • वास्तव में क्या "for है:

    A.each do |i| 
        # some code 
    end 
    

    for कर्नेल तरीका नहीं है "रूबी

  • समान चीजों को करने के लिए अन्य कीवर्ड का उपयोग करने का कोई तरीका है ?

कुछ की तरह:

total = sum i in I {x[i]} 

मानचित्रण करने के लिए:

total = I.sum {|i] x[i]} 

उत्तर

45

यह लगभग वाक्यविन्यास चीनी है। एक अंतर यह है कि, जबकि for इसके आसपास के कोड के दायरे का उपयोग करेगा, each अपने ब्लॉक के भीतर एक अलग दायरा बनाता है। निम्नलिखित की तुलना करें:

for i in (1..3) 
    x = i 
end 
p x # => 3 

बनाम

(1..3).each do |i| 
    x = i 
end 
p x # => undefined local variable or method `x' for main:Object 
+0

वाह, इतना सूक्ष्म, फिर भी जब मैं इस तरह कुछ चलाता हूं तो आसान हो जाएगा। धन्यवाद! – sivabudh

+0

असल में आपका दूसरा उदाहरण 'नेमइरर फेंकता है: अनिर्धारित स्थानीय चर या विधि' i 'मुख्य के लिए: ऑब्जेक्ट'। ऐसा इसलिए है क्योंकि आप 'do' खो रहे हैं। –

+0

@JakubHampl मैंने इसे ठीक किया। धन्यवाद! –

14

foreach विधि के लिए सिर्फ वाक्य रचना चीनी है। यह इस कोड को चलाकर देखा जा सकता है:

for i in 1 do 
end 

यह त्रुटि में परिणाम है:

NoMethodError: undefined method `each' for 1:Fixnum 
+3

-1 क्योंकि इन दोनों के बीच एक अंतर है, और वे हमेशा समान नहीं होते हैं। – user2398029

9

बस वाक्यात्मक चीनी है।

the pickaxe से

:

For ... In

Earlier we said that the only built-in Ruby looping primitives were while and until. What's this ``for'' thing, then? Well, for is almost a lump of syntactic sugar. When you write

for aSong in songList 
    aSong.play 
end 

Ruby translates it into something like:

songList.each do |aSong| 
    aSong.play 
end 

The only difference between the for loop and the each form is the scope of local variables that are defined in the body. This is discussed on page 87.

You can use for to iterate over any object that responds to the method each, such as an Array or a Range.

for i in ['fee', 'fi', 'fo', 'fum'] 
    print i, " " 
end 
for i in 1..3 
    print i, " " 
end 
for i in File.open("ordinal").find_all { |l| l =~ /d$/} 
    print i.chomp, " " 
end 

produces:

fee fi fo fum 1 2 3 second third 

As long as your class defines a sensible each method, you can use a for loop to traverse it.

class Periods 
    def each 
    yield "Classical" 
    yield "Jazz" 
    yield "Rock" 
    end 
end 


periods = Periods.new 
for genre in periods 
    print genre, " " 
end 

produces:

Classical Jazz Rock 

रूबी (योग उदाहरण आप ऊपर बनाया की तरह) सूची comprehensions के लिए अन्य खोजशब्दों जरूरत नहीं है। for एक बहुत लोकप्रिय कीवर्ड नहीं है, और विधि वाक्यविन्यास (arr.each {}) आम तौर पर पसंद किया जाता है।

संबंधित मुद्दे