ruby> for num in (4..6) | print num,"\n" | end 4 5 6 4..6
也可以是其它的什么類型的集合,比如一個數(shù)組:
ruby> for elt in [100,-9.6,"pickle"] | print "#{elt}\t(#{elt.type})\n" | end 100 (Fixnum) -9.6 (Float) pickle (String) [100, -9.6, "pickle"]
但我們說過頭了.for其實是 each 的另一寫法,正巧,這是我們關(guān)于迭代器的第一個例子.下面的兩種形式是等價的:
# If you're used to C or Java, you might prefer this. for i in collection ... end # A Smalltalk programmer might prefer this. collection.each {|i| ... }