looping loops in ruby (noob) [closed]
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...
精彩评论