DEV Community

Discussion on: For Loop in different programming languages

Collapse
 
ben profile image
Ben Halpern

Love the apples-to-apples comparison.

Here's Ruby:

for num in 0..max_num do
   puts "The number is #{num}"
end

But in practice, nobody uses for loops.

Here's a while:

while num < max_num  do
   puts("The number is #{num}" )
   num +=1
end

But nobody uses those either.

People are way more likely to do

(0..max_num).each do |num|
   puts "The number is is #{num}"
end

Or using a collection of objects, like an array or an ActiveRecord collection.

pizza_toppings.each do |topping|
   puts "The topping is #{topping.name}"
end
Collapse
 
rattanakchea profile image
Rattanak Chea

Thank you for adding Ruby syntax. This post was written a few year ago when I found myself always scrambling to write loop when working with different programming languages. Nowadays, a functional programming approach is preferable. I love Python and Ruby for their clean syntax.

Collapse
 
rattanakchea profile image
Rattanak Chea

Do you mind if I include your Ruby code into the post? I will put credit where it belongs.

Collapse
 
ben profile image
Ben Halpern

Go for it. And no need to credit if it effects the reading in any way. πŸ™‚