开发者

looping loops in ruby (noob) [closed]

开发者 https://www.devze.com 2022-12-19 23:44 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can开发者_如何学Go be reopened, visit the help center. Closed 10 years ago.
n = 0
m = 40
o = 0
while n < m 
n = n + 1
end
while n = m 
o = o + 1 
n = 0 
end

With that code, what would be the best way to make it so once it went through the second loop it would go back through the first???

Any help for this beginner is welcomed. :)


Are you looking for something like this?

n = 0
m = 40
o = 0
while n < m 
  n = n + 1
  if (n == m) {
    o = o + 1
    n = 0
  }
  // as pointed out by Samir, you might want to put
  // termination condition here, else it will loop infinitely
end


Not entirely sure you've given us enough information to solve this one. I'm not sure what you are trying to do.

It would be unusual to use while like this in Ruby. There are lots of better ways to iterate. For example, if you are walking through an array, you can do:

my_array.each do |e|
   # e is the next element of my_array
end

If you are walking through a string, you can do:

my_string.each_char do |c|
   # c is the next character in my_string
end

If you really want a counter, you can use each_with_index for an array, or for a string:

(1..my_string.size).each do |i|
   c = my_string[i - 1]
   # now c = next character, i = index
end

Not a direct answer to your question, I admit, but DJ & DigitalRoss are correct, you seem to be working towards nested loops.


Nested loops, maybe?

Are you looking for something like this:

(0..2).each do |o|
  (0..4).each do |n|
    p [o, n]
  end
end

Adjust the loop boundaries as you like...

0

精彩评论

暂无评论...
验证码 换一张
取 消