Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is prefered way to loop in Ruby?

Why is each loop preferred over for loop in Ruby? Is there a difference in time complexity or are they just syntactically different?

like image 676
nimeshkiranverma Avatar asked Jul 25 '14 06:07

nimeshkiranverma


People also ask

What is the preferred way of iterating through a list of objects in Ruby?

The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.

Why loop is preferred over while loop?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.

Is there for loop in Ruby?

“for” loop has similar functionality as while loop but with different syntax. for loop is preferred when the number of times loop statements are to be executed is known beforehand. It iterates over a specific range of numbers.

What are the 3 types of loops?

Loops are control structures used to repeat a given section of code a certain number of times or until a particular condition is met. Visual Basic has three main types of loops: for.. next loops, do loops and while loops.


1 Answers

Yes, these are two different ways of iterating over, But hope this calculation helps.

require 'benchmark'

a = Array( 1..100000000 )
sum = 0
Benchmark.realtime {
  a.each { |x| sum += x }
}

This takes 5.866932 sec

a = Array( 1..100000000 )
sum = 0
Benchmark.realtime {
  for x in a
    sum += x
  end
}

This takes 6.146521 sec.

Though its not a right way to do the benchmarking, there are some other constraints too. But on a single machine, each seems to be a bit faster than for.

like image 66
Anil Purohit Avatar answered Sep 25 '22 00:09

Anil Purohit