我有一段代码可以在 ruby 中检查 nil。所以我想要实现的是:
例如,如果我调用 get_score_value(nil,(nil-1))
。我希望 ruby 延迟 nil-1
的评估,直到它到达 get_score_value
函数,而不是在它被传递给函数之前评估它。换句话说,我想将数学表达式作为参数传递给方法。
在 ruby 中最优雅的方法是什么?非常感谢
def get_score_value(value,value2)
value.nil? ? "NULL" : value2.round(2)
end
更新:
我才发现这个问题其实和懒惰严格评价的话题有关。 (以下内容来自这个很棒的网站: http://www.khelll.com/blog/ruby/ruby-and-functional-programming/
Strict versus lazy evaluation
Strict evaluation always fully evaluates function arguments before invoking the function. Lazy evaluation does not evaluate function arguments unless their values are required to be evaluated. One use of Lazy evaluation is the performance increases due to avoiding unnecessary calculations.
However as the following example shows, Ruby use Strict evaluation strategy:
print length([2+1, 3*2, 1/0, 5-4]) =>ZeroDivisionError: divided by 0
The third parameter of the passed array contains a division by zero operation and as Ruby is doing strict evaluation, the above snippet of code will raise an exception.
最佳答案
您可能有兴趣使用 Proc...
func = Proc.new {|n| n -1 }
def get_score_value(value, proc)
if value.nil?
return proc.call(0)
end
end
p get_score_value(nil, func)
你的 proc 就像一个普通的方法,它仍然可以测试 nil 之类的东西。
或者,它允许您提供单独的函数来处理这些情况:
func1 = Proc.new {|n| n -1 }
func2 = Proc.new { "was nil" }
def check_for_nil(value, funcNil, funcNotNil)
if value.nil?
return funcNil.call()
else
return funcNotNil.call(value)
end
end
p check_for_nil(nil, func2, func1)
p check_for_nil(1, func2, func1)
另请注意,在您只想将其转换为空或默认输入类型(即使用 0 表示数字,[] 表示数组等)的情况下,可能会使用 或
关键字.)
def get_score_value(value)
(value or 0).round(2)
end
关于ruby-on-rails - 如何对 Ruby 参数进行惰性求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7031804/