0

我得到了下面的 Rake 任务,它每天运行一个来结算我的应用程序中的一些赌注。但我很确定它可以被简单化,所以 IF-THEN 语句可以替换为 s CASE 词干。

我假设多个 IF 语句的运行时间比使用 CASE 选项的相同进程要长。那是对的吗?

我只是不确定如何将它从 IF-THEN 转换为 CASE 选项..

task :settle => :environment do
  @bets = Bet.where(:settle => false)

  @bets.each do |bet|

    if not bet.value.nil?

     if bet.price.value > bet.value and bet.buy == true then 
      bet.profitloss  = 10
      bet.settle      = true
      bet.save
     end

     if bet.price.value < bet.value and bet.buy == false then
      bet.profitloss  = 10
      bet.settle      = true
      bet.save
     end

     if bet.price.value > bet.value and bet.buy == false then
      bet.profitloss  = -10
      bet.settle      = true
      bet.save
     end

     if bet.price.value < bet.value and bet.buy == true then
      bet.profitloss  = -10
      bet.settle      = true
      bet.save
     end

     if bet.price.value = bet.value then
      bet.profitloss  = -10
      bet.settled     = true
      bet.save
     end 

   end
  end
end
4

2 回答 2

3

这似乎是

bet.settle 始终为 true bet.profitloss 为 -10,除非 (bet.price.value > bet.value and bet.buy) 或 (bet.price.value < bet.Value and !bet.buy) 在这种情况下为 10

从下面的真值表得到这个

< bet | = bet | > bet | buy || settle || profit
  0   |   0   |   1   |  0  ||    1   ||   0
  0   |   0   |   1   |  1  ||    1   ||   1
  0   |   1   |   0   |  0  ||    1   ||   0
  0   |   1   |   0   |  1  ||    1   ||   0
  1   |   0   |   1   |  0  ||    1   ||   1
  1   |   0   |   1   |  1  ||    1   ||   0

因此,您几乎可以使用一个 if 语句来完成整个事情,但可以通过测试进行编织。:)

于 2012-09-29T20:17:41.170 回答
2

也许你可以像这样实现它:

task :settle => :environment do
@bets = Bet.where(:settle => false)

@bets.each do |bet|
  if not bet.value.nil?
    case 
    when bet.price.value > bet.value and bet.buy == true
      profitloss  = 10
    when bet.price.value < bet.value and bet.buy == false 
      profitloss  = 10
    when bet.price.value > bet.value and bet.buy == false
      profitloss  = -10
    when bet.price.value < bet.value and bet.buy == true 
      profitloss  = -10
    when bet.price.value = bet.value
      profitloss  = -10
    end
    if profitloss  
      bet.settled = true
      bet.profitloss = profitloss 
      bet.save
    end 
  end
end

取出已解决并保存的东西可以让您在需要时轻松集成其他功能,而无需在每个 if 或 when 情况下复制它。

于 2012-09-29T20:07:41.647 回答