我用Ruby创建了一个乒乓球测试它用一个新方法Fixnum修补ping_pong类,该方法在(0..self)范围内循环,检查每个元素上的某些条件,并构造结果数组。
结果数组将有Ping表示可被3整除的范围内的数字,Pong表示可被5整除的数字,Ping-Pong表示可被两者整除的数字。
我现在的问题是,为什么代码只有在以下情况下才能工作:

elsif (num.%(3) == 0) && (num.%(5) == 0) array.push("Ping-Pong")

领先于其他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

最佳答案

当多个if/elsif块链接在一起时,只有其中一个块将运行,第一个具有真条件的块将是要运行的块所以,区块的顺序很重要例如:

if true
  puts 'this code will run'
elsif true
  puts 'this code will not run'
end

尽管这些块的条件都是正确的,但只有第一个块是运行的如果要同时运行这两个块,请使用两个独立的if块,如下所示:
if true
  puts 'this code will run'
end

if true
  puts 'this code will also run'
end

10-01 07:16
查看更多