Ruby - 返回LATEST条件匹配,而不是第一个条件匹配

时间:2017-08-13 03:13:05

标签: ruby if-statement switch-statement boolean conditional-statements

下面的假设案例陈述考虑了三个变量:

  • 名称
  • 年龄
  • garlic_allergy

通过下面的案例陈述,我们的目标是获得"结果"变量更新到LATEST条件,而不是第一个条件匹配。例如如果用户输入变量age = 90,garlic_allergy = false,name = Dracula,则case语句应该返回"肯定是吸血鬼" (满足最新条件)而不是"可能不是吸血鬼" (满足第一个条件)。

    case
    when age.to_i < 100 && garlic_allergy = false
      result = "Probably NOT a vampire"
    when age.to_i < 100 && garlic_allergy = true 
      result = "Maybe a vampire"
    when age.to_i > 100 && garlic_allergy = true
      result = "almost certainly a vampire"
    when name = "Dracula"
      result = "Definitely a vampire"
    else
      result = "Results inconclusive"  
    end

    puts result
    end

这是一个示例,但是试图找出如何为任何case语句或if / elsif / else语句执行此操作以及多个条件等...如何确保程序在每个时间运行/ elsif声明并返回最新条件。我尝试通过将语句包装在循环中来实现它,但还没有运气。

1 个答案:

答案 0 :(得分:0)

根据您的条件构建数组

conditions = []

conditions.push lambda { |name, age, garlic_allergy|
  'Probably NOT a vampire' if age < 100 and not garlic_allergy
}

conditions.push lambda { |name, age, garlic_allergy| 
  'Maybe a vampire' if age < 100 and garlic_allergy
}

conditions.push lambda { |name, age, garlic_allergy|
  'almost certainly a vampire' if age > 100 and garlic_allergy
}

conditions.push lambda { |name, age, garlic_allergy|
  'Definitely a vampire' if name == 'Dracula'
}

将你的条件减少到最后一个成功的条件。

result = conditions.inject('Results inconclusive') { |current, x|
  r = x.(name, age, garlic_allergy)

  r != nil ? r : current
}

请注意,inject的初始值是回退条件,如果没有条件成功,将保留该条件。