the*_*gah 5 ruby variables counter loops
我忘记了如何跟踪Ruby中循环的位置.通常我用JavaScript,AS3,Java等编写.
each:
counter = 0
Word.each do |word,x|
   counter += 1
   #do stuff
end 
for:
一样
while:
一样
block
Word.each  {|w,x| }
这个我真的不知道.
除了Ruby 1.8的Array#each_with_index方法之外,Ruby 1.9中的许多枚举方法在没有块的情况下调用时返回一个Enumerator; 然后,您可以调用该with_index方法让枚举器也传递索引:
irb(main):001:0> a = *('a'..'g')
#=> ["a", "b", "c", "d", "e", "f", "g"]
irb(main):002:0> a.map
#=> #<Enumerator:0x28bfbc0>
irb(main):003:0> a.select
#=> #<Enumerator:0x28cfbe0>
irb(main):004:0> a.select.with_index{ |c,i| i%2==0 }
#=> ["a", "c", "e", "g"]
irb(main):005:0> Hash[ a.map.with_index{ |c,i| [c,i] } ]
#=> {"a"=>0, "b"=>1, "c"=>2, "d"=>3, "e"=>4, "f"=>5, "g"=>6}
如果您想要map.with_index或select.with_index(或类似)在Ruby 1.8.x下,您可以做这个无聊但快速的方法:
i = 0
a.select do |c|
  result = i%2==0
  i += 1
  result
end
或者你可以有更多的功能乐趣:
a.zip( (0...a.length).to_a ).select do |c,i|
  i%2 == 0
end.map{ |c,i| c }
如果您使用each_with_index而不是each,您将获得索引以及元素.所以你可以这样做:
Word.each_with_index do |(word,x), counter|
   #do stuff
end
对于while循环,你仍然需要自己跟踪计数器.