Next! (9/18)


#1

Hi All,

I was just wondering, which one is the better practice? What are the pros & cons for each one?

This one:

i = 20
until i =< 0
  i -=1
  next if i % 2 != 0
  print "#{i}"
end

Or this:

i = 20
loop do
  i -= 1
  next if i % 2 != 0
  print "#{i}"
  break if i <= 0
end

Thank you in advance.


#2

That is not really a question of practice, but a choice of logic. We never want to gray out those choices. Best practice leans toward other things, not that.

As for pro’s and con’s, I see this as subjective and only comes into question when setting up one’s code design. It might point to a preference for one style of logic over another. What ever that preference may be, let it be obvious and applied in your design on a consistent basis. Don’t leave anybody guessing which you prefer and intended to use.


#3

Thanks @mtf for your insight. So it’s a matter of consistency.


#4

I contend that if it does the job, it does the job.
There may be ways that look “prettier”. I think it’s all about having a style that’s readable and consistent. While mostly following standard practices.

Of course those practices can change based on project, place of employment, etc.

Typically it’s the “Ruby way” to avoid loops. Here is a more traditional ruby way to print the odds in a range.

(1..20).each {|i| puts i if i % 2 != 0}

It’s important to know/great that you’re already seeing that there are a million ways to do the same thing, especially in ruby.


#5

Hi @fight_dragons, nice tight code you got there. Thank you for the inspiration.
But how to make that print in order from 20 to lower number (not ascending)?


#6

There are tons of ways to do that.
Here is a fun one

(1..20).reverse_each {|i| puts i if i % 2 != 0}


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.