我在Ruby中创建了一个乒乓球测试.它Fixnum使用一种新方法修补类ping_pong,它在一个范围内循环(0..self),检查每个元素的一些条件,并构造一个结果数组.
所得阵列将具有Ping用于在由整除范围内的数3,Pong用于通过整除数5,和Ping-Pong用于数字整除两者.
我现在的问题是,为什么代码只适用于以下部分:
elsif (num.%(3) == 0) && (num.%(5) == 0) array.push("Ping-Pong")
Run Code Online (Sandbox Code Playgroud)
领先于其他elsif声明?我尝试将它放在另一个之后,elsif但它没有用.
这是我的代码:
class Fixnum
define_method(:ping_pong) do
array = [0]
total = (0..self)
total = total.to_a
total.each() do |num|
if (num == 0)
array.push(num)
elsif (num.%(3) == 0) && (num.%(5) == 0)
array.push("Ping-Pong")
elsif (num.%(3) == 0)
array.push("Ping")
elsif (num.%(5) == 0)
array.push("Pong")
else
array.push(num)
end
end
array
end
end
Run Code Online (Sandbox Code Playgroud)
如果将多个if/ elsif块链接在一起,则只会运行其中一个,并且第一个具有真实条件的块将是要运行的块.所以,块的顺序很重要.例如:
if true
puts 'this code will run'
elsif true
puts 'this code will not run'
end
Run Code Online (Sandbox Code Playgroud)
即使这些块的条件都是真的,也只运行第一个块.如果要同时运行,请使用两个单独的if块,如下所示:
if true
puts 'this code will run'
end
if true
puts 'this code will also run'
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
131 次 |
| 最近记录: |