Ruby - 我可以将此逻辑移动到全局变量吗?

时间:2014-05-26 13:55:38

标签: ruby global-variables next continue

在一个实例中,在方法中,我遍历列表lines并操纵每个line。但是,我想跳过一些lines。我想定义哪个lines要跳过实例顶部的一些全局变量。那可能吗?我怎样才能做到这一点?

class Bets

  #stuff

  def make_prediction 
    lines.each do |line|
      next if @league == :nba && line[:bet_type] == :total && line[:period] == :h1
      next if [:total, :spread, :money_line].include?(line[:bet_type]) && line[:period] == :fg
      #do stuff
    end
  end
end

编辑:

有人投票支持这个话题被视为无益,因为目前还不清楚。我不确定它有什么不清楚的地方。但我会更清楚地表达我希望它看起来......

class Bets
  #psuedo code, obviously this wont work
  #and i cant think how to make it work
  #or if its even possible
  GLOBAL = true if @league == :nba & line[:bet_type] == :total & line[:period] == :h1 

  #stuff

  def make_prediction 
    lines.each do |line|
      next if GLOBAL #psuedo code
      #do stuff
    end
  end
end

2 个答案:

答案 0 :(得分:1)

使用方法怎么样:

class Bets

  def skip?  
    @league == :nba & line[:bet_type] == :total & line[:period] == :h1 
  end
  #stuff

  def make_prediction 
    lines.each do |line|
      next if skip?          
      #do stuff
    end
  end
end

全局变量在很大程度上不受欢迎,因此请尝试找到测试有意义的上下文。

答案 1 :(得分:0)

尝试创建Proc并在实例的上下文中执行它

GLOBAL = Proc.new {|line| your_code_goes_here}
#...
#...
def make_prediction 
  lines.each do |line|
    next if instance_exec(line,GLOBAL) #psuedo code
    #do stuff
  end
end