0

I have a variable x which is set to 10. And I want to write a while loop that increments that. I know you can easily just use a for-loop for this, but easy isn't fun. The code I have is:

def add(a)
   g = a + 1
   puts g
end

def loop(d)
   x = 0
   while x <= 4
       x += 1
       add(d)
   end
end

loop(9)

When ran I get 9, four times. How can I get this code to have an output of 9, 10, 11, 12?

3
  • 2
    There are so many problems with this code (besides x was never set to 10, what contradicts the preface,) that there is no way to fix it save for completely rewrite from the scratch after reading a book on ruby language. Commented Jun 23, 2016 at 8:51
  • x is set to 0, not 10 and your code outputs 10 four times, not 9. Please fix either your code or your question. Commented Jun 23, 2016 at 8:56
  • What is your expected output ? array of numbers 9 to 12 ? Commented Jun 23, 2016 at 10:25

2 Answers 2

1

Your problem is that you say add(d) and d is the parameter of your loop, loop(d). Ruby does blindly what you tell him : loop(9), so here d=9 and remains equal to 9. You need to increment the value of d. To do that add will now return the incremented value, and we assign the returned value to d (in loop).

To solve your problem you will want to do something like :

def add(a)
   g = a + 1
   puts g
   g
end

def loop(d)
   x = 0
   while x <= 4
       x += 1
       d = add(d)
   end
end

loop(9)

BUT and that's a huge but, your code is not the ruby way at all.

If I were to do it I would do it like this:

def loop(start_number, repeat_number, increment)
  repeat_number.times do
    start_number += increment
    p start_number
  end
end

loop(9, 4, 1)
Sign up to request clarification or add additional context in comments.

Comments

0

If you rly wanna to use while and your expected outpit is Array numbers 9 up to 12.

Simply define the array variable before while loop and return it like this:

def loop(number)
  x, a = 0, []
  while x <= 3
    a << number + x
    x += 1
  end
  a
end

loop(9)
# => [9, 10, 11, 12]

BETTER WAY

But better way is use some ruby functions like times and map

in this case we use times and map

def loop(d)
  4.times.map{|i| d + i}
end

p loop(9)
# => [9, 10, 11, 12]

maybe this will helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.