DEV Community

Discussion on: Understanding Ruby - For vs Each

Collapse
 
vgoff profile image
Victor Goff

Note that the range doesn't need to be converted to an array for this to work. And line 2 in the for vs loop example is invalid Ruby code, and so it raises an exception.

The code may be written like this (to include the comparison of the reports):

require 'benchmark/ips'

collection = (1..100)

Benchmark.ips do |bench|
  bench.report("for loop") do
    sum = 0
    for item in collection
      sum += item
    end
    sum
  end

  bench.report("each loop") do
    sum = 0
    collection.each do |item|
      sum += item
    end
    sum
  end

  bench.compare!
end
Enter fullscreen mode Exit fullscreen mode
Collapse
 
baweaver profile image
Brandon Weaver

Line 2 was me forgetting to comment the line. The collection doesn't explicitly need to be an Array, no. Also compare! doesn't need to be explicitly called.

Collapse
 
vgoff profile image
Victor Goff • Edited

Also compare! doesn't need to be explicitly called.

This is true, but it then won't give you the comparison report. So it does not need to be there, it is just a nice to have. Also, not sure how to implicitly call it. To be sure, I did write in the message that it was there to show the comparison report.