ruby> for num in (4..6) | print num,"/n" | end 4 5 6 4..6
也可以是其它的什么类型的集合,比如一个数组:
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 的另一写法,正巧,这是我们关于迭代器的第一个例子.下面的两种形式是等价的:
# 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| ... }