"nil or zero "的最佳ruby成语[英] Best ruby idiom for "nil or zero"

本文是小编为大家收集整理的关于"nil or zero "的最佳ruby成语的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在寻找一种简洁的方式来检查一个值,以查看它是零还是零.目前,我正在做类似:

的事情
if (!val || val == 0)
  # Is nil or zero
end

但这似乎很笨拙.

推荐答案

对象具有 nil? nil?/em>方法.

if val.nil? || val == 0
  [do something]
end

或仅需一个指令:

[do something] if val.nil? || val == 0

其他推荐答案

从Ruby 2.3.0开始,您可以将安全导航操作员(&.)与 Numeric#nonzero? . &.返回nil如果实例为nil和nonzero? - 如果数字为0:

unless val&.nonzero?
  # Is nil or zero
end

或Postfix:

do_something unless val&.nonzero?

其他推荐答案

如果您真的喜欢结尾处有问号的方法名称:


if val.nil? || val.zero?
  # do stuff
end

您的解决方案也可以,其他一些解决方案也可以.

Ruby可以让您寻找一种很好的方法来完成所有操作,如果您不小心.

本文地址:https://www.itbaoku.cn/post/627745.html

问题描述

I am looking for a concise way to check a value to see if it is nil or zero. Currently I am doing something like:

if (!val || val == 0)
  # Is nil or zero
end

But this seems very clumsy.

推荐答案

Objects have a nil? method.

if val.nil? || val == 0
  [do something]
end

Or, for just one instruction:

[do something] if val.nil? || val == 0

其他推荐答案

From Ruby 2.3.0 onward, you can combine the safe navigation operator (&.) with Numeric#nonzero?. &. returns nil if the instance was nil and nonzero? - if the number was 0:

unless val&.nonzero?
  # Is nil or zero
end

Or postfix:

do_something unless val&.nonzero?

其他推荐答案

If you really like method names with question marks at the end:


if val.nil? || val.zero?
  # do stuff
end

Your solution is fine, as are a few of the other solutions.

Ruby can make you search for a pretty way to do everything, if you're not careful.