Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple counter for loops ruby

Tags:

ruby

For the ruby .times do is there a counter or do I have to do the following

count = 0
4.times do
puts "this is the count #{count}"
count = count+1
like image 655
chell Avatar asked Sep 01 '11 08:09

chell


People also ask

Are there for loops in Ruby?

In Ruby, for loops are used to loop over a collection of elements. Unlike a while loop where if we're not careful we can cause an infinite loop, for loops have a definite end since it's looping over a finite number of elements.

How do you end a loop in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.

What does .times do in Ruby?

The times function in Ruby returns all the numbers from 0 to one less than the number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead.

How do you stop an infinite loop in Ruby?

This means that the loop will run forever ( infinite loop ). To stop this, we can use break and we have used it. if a == "n" -> break : If a user enters n ( n for no ), then the loop will stop there. Any other statement of the loop will not be further executed.


1 Answers

Yes, times yields a counter:

4.times do |count|
  puts "this is the count #{count}"
end
like image 96
sepp2k Avatar answered Nov 11 '22 10:11

sepp2k