Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 thing

while:

same thing

block

Word.each  {|w,x| }

This one I really don't know about.

like image 541
thenengah Avatar asked Jan 04 '11 00:01

thenengah


People also ask

Is there a for loop in Ruby?

In Ruby, for loops are used to loop over a collection of elements.

How do you skip iterations in Ruby?

skip to the next iteration while part way through the current interation – this is done using the “next” keyword. exit the loop early – this is done using the “break” keyword. redo the current iteration – this is done using the “redo” keyword.


1 Answers

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 }
like image 171
Phrogz Avatar answered Nov 10 '22 13:11

Phrogz