Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for a for loop in ruby

Tags:

syntax

ruby

How do I do this type of for loop in Ruby?

for(int i=0; i<array.length; i++) {  } 
like image 392
DNB5brims Avatar asked Jan 09 '10 09:01

DNB5brims


People also ask

How do you write a for loop in Ruby?

The simplest way to create a loop in Ruby is using the loop method. loop takes a block, which is denoted by { ... } or do ... end . A loop will execute any code within the block (again, that's just between the {} or do ...

What is the syntax a for loop?

Syntax of a For LoopThe initialization statement describes the starting point of the loop, where the loop variable is initialized with a starting value. A loop variable or counter is simply a variable that controls the flow of the loop. The test expression is the condition until when the loop is repeated.

What Is syntax of for loop give example?

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number.


1 Answers

array.each do |element|   element.do_stuff end 

or

for element in array do   element.do_stuff end 

If you need index, you can use this:

array.each_with_index do |element,index|   element.do_stuff(index) end 
like image 146
Eimantas Avatar answered Oct 14 '22 04:10

Eimantas