How To keep track of counter variables in ruby, block, for, each, do
I forget how to keep track of the position of the loops in Ruby. Usually I write in JavaScript, AS3, Java, etc.
each
:
counter = 0
Word.each do |word,x|
counter += 1
#do stuff
end
for
:
same th开发者_运维问答ing
while
:
same thing
block
Word.each {|w,x| }
This one I really don't know about.
In addition to Ruby 1.8's Array#each_with_index
method, many enumerating methods in Ruby 1.9 return an Enumerator when called without a block; you can then call the with_index
method to have the enumerator also pass along the 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}
If you want map.with_index
or select.with_index
(or the like) under Ruby 1.8.x, you can either do this boring-but-fast method:
i = 0
a.select do |c|
result = i%2==0
i += 1
result
end
or you can have more functional fun:
a.zip( (0...a.length).to_a ).select do |c,i|
i%2 == 0
end.map{ |c,i| c }
If you use each_with_index
instead of each
, you'll get an index along with the element. So you can do:
Word.each_with_index do |(word,x), counter|
#do stuff
end
For while
loops you'll still have to keep track of the counter yourself.
A capital W would mean it's a constant which most likely mean it's a class or a module not an instance of a class. I guess you could have a class return an enumerable using each but that seems very bizarre.
To remove the confusing extra junk and the, possibly, incorrectly capitalized example I would make my code look like this.
words = get_some_words()
words.each_with_index do |word, index|
puts "word[#{index}] = #{word}"
end
I'm not sure what Sepp2K was doing with the weird (word,x) thing.
精彩评论