Ruby如何从方法返回&&或||等逻辑运算符?
动态切换Ruby逻辑运算符的解决方案
你不能直接返回&&或||,因为它们是Ruby的语法关键字,不是可以返回或传递的对象/方法。要实现动态逻辑运算,有几种可行的方式:
方法1:使用Lambda/Proc封装逻辑
这种方式能保留&&和||的短路特性,是最推荐的方案:
module Rules::Engine module_function def call a = true b = false operator = logic(a) ap "what does this return #{operator.call(a, b)}" end def logic(condition) # 根据条件返回对应逻辑的Lambda condition ? ->(x, y) { x && y } : ->(x, y) { x || y } end end
Lambda会封装&&或||的逻辑,你可以通过call方法传入参数执行运算,完全保留短路行为(比如false && expensive_call不会执行expensive_call)。
方法2:用符号+send调用对应方法
如果你的场景不需要短路特性,可以用Ruby的位运算方法&和|(对布尔值来说,它们的结果和逻辑运算一致):
module Rules::Engine module_function def call a = true b = false operator = logic(a) ap "what does this return #{a.send(operator, b)}" end def logic(condition) condition ? :& : :| end end
⚠️ 注意:&和|不会短路,无论左边结果如何,右边表达式都会被计算。如果你的逻辑依赖短路优化,不要用这种方式。
方法3:直接封装逻辑运算
如果不需要传递运算符,只是需要根据条件应用不同逻辑,直接写在方法里更简单:
module Rules::Engine module_function def call a = true b = false ap "what does this return #{apply_logic(a, b)}" end def apply_logic(x, y) # 这里可以替换成任意动态判断逻辑 x ? (x && y) : (x || y) end end
内容的提问来源于stack exchange,提问作者ToddT
相关产品推荐
相关产品推荐

