user7496931
user7496931

Reputation:

Trying to write a simple countdown loop in pairs with Ruby

This instructions are as follow:

NUMBER CRUNCHER

Write a method that takes a number as an argument If the number is greater than 20 count down from the number by 2's If the number is less than 20 count down from the number by 1's Display the numbers as they count down to 0.

I have written this, but it's not doing what it's supposed. Any help?

def num_cruncher(num)
count = num

until count == 0 do
    if num > 20
        puts count - 2
    else
        puts "#{count}"
    end
        count -= 1
  end
end

Upvotes: 0

Views: 648

Answers (2)

Sagar Pandya
Sagar Pandya

Reputation: 9497

You can use Numeric#step here. Something like this:

def num_cruncher n
  s = n > 20 ? -2 : -1
  n.step(by: s, to: 0).entries
end

num_cruncher 23
#=> [23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1]

Upvotes: 1

Eric Duminil
Eric Duminil

Reputation: 54223

Here's your code, with as few changes as possible :

def num_cruncher(num)
  count = num

  until count < 0 do
    puts count
    if num > 20
      count -= 2
    else
      count -= 1
    end
  end
end

num_cruncher(10)
# 10
# 9
# 8
# 7
# 6
# 5
# 4
# 3
# 2
# 1
# 0

num_cruncher(21)
# 21
# 19
# 17
# 15
# 13
# 11
# 9
# 7
# 5
# 3
# 1

By extracting the if-statement outside of the loop, the code becomes a bit shorter :

def num_cruncher(num)
  if num > 20
    step = 2
  else
    step = 1
  end

  until num < 0 do
    puts num
    num -= step
  end
end

Upvotes: 2

Related Questions