I'm learning Ruby On Rails program and I've came to a road block on one of the lessons. The assignment has me creating an odd numbers for the script to read starting from "20 to 0" using the next
component. This is the example they've given me to change :
我正在学习Ruby On Rails程序,我在其中一节课上遇到了障碍。作业要求我创建一个奇数,以便使用下一个组件从“20到0”读取脚本。这是他们给我的改变的例子:
i = 20
loop do
i -= 1
print "#{i}"
break if i <= 0
end
This is the problem:
这就是问题所在:
Add a line to your loop before your print statement. Use the
next
keyword so that you skip to the next iteration if the number i is odd.在打印语句之前向循环中添加一行。使用下一个关键字,如果数字i是奇数,则跳到下一个迭代。
How do I accomplish this?
我如何做到这一点?
3 个解决方案
#1
5
You can just insert a next
that skips the rest of the loop if the number is odd:
你可以插入一个下一个,如果这个数字是奇数,就跳过这个循环的其余部分:
i = 20
loop do
i -= 1
next if i.odd?
puts "#{i}"
break if i <= 0
end
#2
1
I would solve it this way:
我可以这样来解:
i = 20
loop do
i -= 1
next if i%2 != 0
print "#{i}"
break if i <= 0
end
#3
0
i = 20
loop do
i -= 1
next if i % 2 == 0
print "#{i}"
break if i <=1
end
#1
5
You can just insert a next
that skips the rest of the loop if the number is odd:
你可以插入一个下一个,如果这个数字是奇数,就跳过这个循环的其余部分:
i = 20
loop do
i -= 1
next if i.odd?
puts "#{i}"
break if i <= 0
end
#2
1
I would solve it this way:
我可以这样来解:
i = 20
loop do
i -= 1
next if i%2 != 0
print "#{i}"
break if i <= 0
end
#3
0
i = 20
loop do
i -= 1
next if i % 2 == 0
print "#{i}"
break if i <=1
end